Introduction
API integration is a critical aspect of modern software development, enabling applications to communicate with external services and exchange data. In this guide, we'll explore a step-by-step breakdown of a typical API integration scenario in C#, covering key concepts such as serialization, encryption, HTTP requests, and error handling.
1. Setting Up the API Integration
First, let's define the basic structure of an API integration method in C#.
Code
public static GetdemoWeboutputmodel GetdemoWebmethod(Getdemo_WebInput model)
{
// Constructing the API URL
string apiUrl = APIURL + "controller/methodname/";
try
{
// Creating an instance of GetdemoWeboutputmodel
GetdemoWeboutputmodel obj = new GetdemoWeboutputmodel();
// Serializing the input model to JSON
var Reqjson = new JavaScriptSerializer().Serialize(model);
// Encrypting the serialized JSON string
Reqjson = objEncryptDecrypt.StringEncrypt(Reqjson);
_CommonModel.Getrequestresponse = Reqjson;
// Creating an instance of HttpClient to make the API request
using (HttpClient client = new HttpClient())
{
// Setting the base URL for the HttpClient
client.BaseAddress = new Uri(apiUrl);
// Clearing the default headers and adding 'application/json' as the accepted media type
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Sending a POST request to the API endpoint with serialized _CommonModel
HttpResponseMessage responseMessage = client.PostAsJsonAsync(apiUrl, _CommonModel).Result;
// Checking if the response is successful
if (responseMessage.IsSuccessStatusCode)
{
// Reading the response content as string
var data = responseMessage.Content.ReadAsStringAsync();
// Deserializing the response content into CommonModel
var res = responseMessage.Content.ReadAsAsync<CommonModel>().Result;
// Decrypting the 'Postresponse' property of CommonModel
res.Postresponse = objEncryptDecrypt.StringDecrypt(res.Postresponse);
// Deserializing the decrypted response into GetdemoWeboutputmodel
obj = JsonConvert.DeserializeObject<GetdemoWeboutputmodel>(res.Postresponse);
// Returning the deserialized object
return obj;
}
}
// Returning the initialized obj if the response is not successful or there's an exception
return obj;
}
catch (Exception ex)
{
// Handling any exceptions that occur during the process
// You might want to log the exception details for debugging
// Currently, the method does not return any information about the exception
}
}
VelladuraiPosted Jul 8, 2024, 10:55 AM
JavaScriptSerializer and call Serialize() method by passing the object(BlogSites). It returns JSON data in string format.
VelladuraiPosted Jul 8, 2024, 10:54 AM
E JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
Arnaud DuboisPosted Jul 4, 2024, 6:52 AM
Thank for this article ! I've got a question : why use JavaScriptSerializer rather than JsonSerializer line 10 ?