The following examples are implemented using .NET Framework, version 4.5. You will need to install Microsoft.AspNet.WebApi.Client package.
Place the proper values to the username, password, domain variables.
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace cSharpDemo { class Program { public static HttpClient Client = new HttpClient(); static void Main() { RunAsync().Wait(); } private static async Task RunAsync() { const string username = "USERNAME"; const string password = "PASSWORD"; const string domain = "HOTELIGA_DOMAIN"; Client.BaseAddress = new Uri("https://api.hoteliga.com/v1/"); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var requestToken = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(Client.BaseAddress, "Token"), Content = new StringContent(String.Format("grant_type=password&username={0}&password={1}&domain={2}", username, password, domain)) }; requestToken.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("multipart/form-data"); var bearerResult = await Client.SendAsync(requestToken); var bearerData = await bearerResult.Content.ReadAsStringAsync(); Console.WriteLine(bearerData); Console.ReadLine(); } } }
Place the proper values to token and customerId variables.
For XML response replace the line
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
with the following:
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace cSharpDemo { class Program { public static HttpClient Client = new HttpClient(); static void Main() { RunAsync().Wait(); } private static async Task RunAsync() { const string token = "TOKEN"; const string customerId = "ID"; Client.BaseAddress = new Uri(String.Format("https://api.hoteliga.com/v1/Customer/{0}", customerId)); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await Client.GetAsync(Client.BaseAddress); var data = await result.Content.ReadAsStringAsync(); Console.WriteLine(data); Console.ReadLine(); } } }
Place the proper value to token and the desired data for the new customer.
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace cSharpDemo { class Program { public class Customer { public string LastName { get; set; } public string FirstName { get; set; } public string Email { get; set; } } public static HttpClient Client = new HttpClient(); static void Main() { RunAsync().Wait(); } private static async Task RunAsync() { const string token = "TOKEN"; var customer = new Customer { LastName = "Smith", FirstName = "John", Email = "johnsmith@example.com" }; Client.BaseAddress = new Uri("https://api.hoteliga.com/v1/Customer"); Client.DefaultRequestHeaders.Accept.Clear(); Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await Client.PostAsJsonAsync(Client.BaseAddress, customer); var data = await result.Content.ReadAsStringAsync(); Console.WriteLine(data); Console.ReadLine(); } } }
In this example there is bearer token retrieval, customer retrieval and customer update with specific fields only (using HTTP PUT).
For faster development, dynamic objects are used, but you may consider to use normal classes for better control over serialization and deserialization.
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Dynamic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ApiExample { class Program { private static readonly string Username = "USERNAME"; private static readonly string Password = "PASSWORD"; private static readonly string Domain = "HOTELIGA_DOMAINS"; private static readonly int ReferenceCustomerId = 151; // set a customer ID that exists private static HttpClient HttpClient = new HttpClient { BaseAddress = new Uri("https://api.hoteliga.com/v1") }; static async Task Main() { try { // stage 1: Get API token var bearerToken = await GetBearerToken(Username, Password, Domain); Console.WriteLine($"The bearer token is " + bearerToken); // stage 2: Get customer with reference ID var customerObject = await GetCustomer(bearerToken, ReferenceCustomerId); Console.WriteLine($"Last name is \"{customerObject.lastName}\", first name is \"{customerObject.firstName}\"."); // stage 3: Update customer first name var randomFirstName = Guid.NewGuid().ToString(); Console.WriteLine($"For customer ID {ReferenceCustomerId} we 're setting the first name to be {randomFirstName}"); await UpdateCustomerProperty(bearerToken, ReferenceCustomerId, customerObject.lastName.ToString(), "firstName", randomFirstName); // stage 4: Get customer with reference ID to see the updated first name var customerObjectUpdated = await GetCustomer(bearerToken, ReferenceCustomerId); Console.WriteLine($"Last name is \"{customerObjectUpdated.lastName}\", first name is \"{customerObjectUpdated.firstName}\"."); } catch (Exception ex) { Console.WriteLine($"An error occured: {ex.Message}"); } finally { Console.WriteLine("Finished."); Console.ReadLine(); } } private static async TaskGetBearerToken(string username, string password, string domain) { var request = new HttpRequestMessage(HttpMethod.Post, new Uri(HttpClient.BaseAddress, "Token")); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Content = new StringContent( String.Format("grant_type=password&username={0}&password={1}&domain={2}", username, password, domain), Encoding.UTF8, "multipart/form-data"); var bearerResult = await HttpClient.SendAsync(request); var bearerData = await bearerResult.Content.ReadAsStringAsync(); if(!bearerResult.IsSuccessStatusCode) { var errorObject = JsonConvert.DeserializeObject (bearerData); throw new Exception(errorObject.error_description.ToString()); } var bearerObject = JsonConvert.DeserializeObject (bearerData); return bearerObject.access_token; } private static async Task GetCustomer(string token, int customerId) { var url = new Uri(HttpClient.BaseAddress, $"Customer/{customerId}"); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await HttpClient.SendAsync(request); var data = await result.Content.ReadAsStringAsync(); if (!result.IsSuccessStatusCode) { var errorObject = JsonConvert.DeserializeObject (data); throw new Exception(errorObject.description.ToString()); } var customerObject = JsonConvert.DeserializeObject (data); return customerObject; } private static async Task UpdateCustomerProperty(string token, int customerId, string customerLastName, string propertyName, string propertyValue) { var dictionary = new Dictionary { { "id", customerId.ToString() }, { "lastName", customerLastName }, { propertyName, propertyValue } }; var customer = ConvertDictionaryToDynamicObject(dictionary); var url = new Uri(HttpClient.BaseAddress, "Customer"); var request = new HttpRequestMessage(HttpMethod.Put, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Content = new StringContent(JsonConvert.SerializeObject(customer), Encoding.UTF8, "application/json"); var result = await HttpClient.SendAsync(request); if (!result.IsSuccessStatusCode) { var data = await result.Content.ReadAsStringAsync(); var errorObject = JsonConvert.DeserializeObject (data); throw new Exception(errorObject.description.ToString()); } } private static dynamic ConvertDictionaryToDynamicObject(IDictionary dictionary) { var expandoObject = new ExpandoObject(); var expandoObjectCollection = (ICollection >)expandoObject; foreach (var keyValuePair in dictionary) { expandoObjectCollection.Add(keyValuePair); } dynamic eoDynamic = expandoObject; return eoDynamic; } } }
In this example there is bearer token retrieval, guest retrieval and guest update with specific fields only (using HTTP PUT).
Contrary to the customer manipulation example, in this case normal classes are used (see Guest class). Note how dates are serialized to YYYY-MM-DD by utilizing the JsonConverter annotation in Guest class properties.
Also, note how error/exception handling is done by using a HoteligaError class to deserialize errors.
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace ApiExample { class Program { private static readonly string _username = "USERNAME"; private static readonly string _password = "PASSWORD"; private static readonly string _domain = "HOTELIGA_DOMAIN"; private static readonly int _referenceGuestId = 1; private static HttpClient _httpClient = new HttpClient { BaseAddress = new Uri("https://api.hoteliga.com/v1") }; static async Task Main() { try { var bearerToken = await GetBearerToken(_username, _password, _domain); var guestObject = await GetGuest(bearerToken, _referenceGuestId); Guest guest = new Guest { Id = _referenceGuestId, DateOfBirth = new DateTime(2000, 01, 02), IdDocIssueDate = new DateTime(2000, 03, 04), NationalityCountryId = "ES", IdDocExpirationDate = new DateTime(2020, 05, 06) }; await UpdateGuestProperty(bearerToken, _referenceGuestId, guest); var guestObjectUpdated = await GetGuest(bearerToken, _referenceGuestId); } catch (Exception ex) { Console.WriteLine($"An error occured: {ex.Message}"); } finally { Console.WriteLine("Finished."); Console.ReadLine(); } } private static async TaskGetBearerToken(string username, string password, string domain) { var request = new HttpRequestMessage(HttpMethod.Post, new Uri(_httpClient.BaseAddress, "Token")); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Content = new StringContent( String.Format("grant_type=password&username={0}&password={1}&domain={2}", username, password, domain), Encoding.UTF8, "multipart/form-data"); var bearerResult = await _httpClient.SendAsync(request); var bearerData = await bearerResult.Content.ReadAsStringAsync(); if(!bearerResult.IsSuccessStatusCode) { var errorObject = JsonConvert.DeserializeObject (bearerData); throw new Exception(errorObject.error_description.ToString()); } var bearerObject = JsonConvert.DeserializeObject (bearerData); return bearerObject.access_token; } private static async Task GetGuest(string token, int guestId) { var url = new Uri(_httpClient.BaseAddress, $"Guest/{guestId}"); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var result = await _httpClient.SendAsync(request); var data = await result.Content.ReadAsStringAsync(); if (!result.IsSuccessStatusCode) { var errorObject = JsonConvert.DeserializeObject (data); throw new Exception($"Exception occured while getting the guest: {errorObject.Description}"); } var guestObject = JsonConvert.DeserializeObject (data); return guestObject; } private static async Task UpdateGuestProperty(string token, int guestId, Guest model) { var url = new Uri(_httpClient.BaseAddress, "Guest"); var request = new HttpRequestMessage(HttpMethod.Put, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); request.Content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); var result = await _httpClient.SendAsync(request); var data = await result.Content.ReadAsStringAsync(); if (!result.IsSuccessStatusCode) { var errorObject = JsonConvert.DeserializeObject (data); throw new Exception($"Exception occured while updating the guest: {errorObject.Description}"); } } } public class Guest { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string LastName2 { get; set; } [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")] public DateTime? DateOfBirth { get; set; } [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")] public DateTime? IdDocIssueDate { get; set; } public int IdDocType { get; set; } public string IdDocNumber { get; set; } public string NationalityCountryId { get; set; } public int ProvinceId { get; set; } public int ReservationId { get; set; } public int SalutationId { get; set; } public int IsPrimaryGuest { get; set; } public string IdDocIssueCountryId { get; set; } // missing [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")] public DateTime? IdDocExpirationDate { get; set; } // missing } public class HoteligaError { public string Code { get; set; } public string Description { get; set; } } public class DateFormatConverter : IsoDateTimeConverter { public DateFormatConverter(string format) { DateTimeFormat = format; } } }