01/07/2024


A simple example of calling a rest API from c#, thats then calling Gov's DVLA's API.
( You could create wrapper API's for a number of reasons.. to project the auth methods and security, to have distributed micro services, load balancing, etc)







Current Status
History

Sample
public class CallCarRegDvla
   {

       /// <summary>
       /// make a method to perform an async call to the API. validate the response and process accordingly.
       /// </summary>
       /// <param name="txtReg"></param>
       /// <returns></returns>
       public CarRegResultModel Lookup(string txtReg) {

           CarRegResultModel result = new CarRegResultModel();
           try { 
               var task = Task.Run(async () => await GetRegResult(txtReg));                
               if (task.Result != null) { result = task.Result; }
           }
           catch (Exception ex) {
               LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
           }
           return result;
       }

       /// <summary>
       /// an async call to the API, if an OK response, deseialize the response into our custom class model.
       /// </summary>
       /// <param name="txtReg"></param>
       /// <returns></returns>
       public async Task<CarRegResultModel> GetRegResult(string txtReg) {
           CarRegResultModel result = new CarRegResultModel();
           
           try {
               var options = new RestClientOptions("https://microserviceAPI:5192/api/v1/MOT/GetCar?carReg=" + txtReg)
               {
                   //MaxTimeout = -1,
               };
               var client = new RestClient(options);
               var request = new RestRequest("", Method.Get);
               request.AddHeader("Accept", "text/plain");
               RestResponse response = await client.ExecuteAsync(request);                
               if (response.IsSuccessStatusCode)
               {
                   CarRegResultModel myDeserializedClass = JsonConvert.DeserializeObject<CarRegResultModel>(response.Content);
                   result = myDeserializedClass;
               }
           }
           catch (Exception ex) {
               LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
           }
       
           return result;
       }
   }