locked
Best practices to handle Web API status codes RRS feed

  • Question

  • User-838515130 posted

    Hi all:
    I have a web API project done with .NETCore.

    My web API receives a request from another Service A, with the information I have I need to do some conversion on the data and send it to another Service B.

    I am expecting that Service B send back some response: like OK or NOK. As the number of codes I can get back from Service B are so much. I would like to know which is the best practices to handle those codes?

    As you will see in my code, I get the status code in this way:

       

    var status = (int)response.StatusCode;

    And the I have some if to handle this. Looking at my code it looks like a very poor status code Handling but at moment it is the best I can do. I am kindly asking suggestions to improve this.

    And If I get an exception in the catch block should I send BadRequest as well?

    I am using RestSharp.
    Following my code:

    [HttpPost]
    [Produces("application/json", Type = typeof(MyModel))]
    public async Task<IActionResult> Post([FromBody]MyModel myModel)
    {
    	try
    	{
    		if (!ModelState.IsValid)
    		{
    			return BadRequest(ModelState);
    		}
    
    		var response = (RestResponse) await _restHelper.GetResponse("serviceB:url", myModel);
                    if (response != null)
                    {
                        var status = (int)response.StatusCode;
                        //2xx status OK
                        if (status >= 200 && status < 300)
                        {
                            return Ok(response.Content);
                        }
                        //Catch all status code
                        return StatusCode(status, response.Content);
                    }
                    //If for some reason, I don't get any response
                    return NotFound("No response");
    	}
    	catch (Exception ex)
    	{
    		_logger.LogError("POST_ERROR", "serviceB-relay/Post UNEXPECTED ERROR", ex.Message);   
    		return BadRequest("Not able to process your request");
    	}
    }

    and this is my restHelper

    public class RestHelper: IRestHelper
    {
    	private readonly IConfigurationRoot _config;
    
    	public RestHelper(IConfigurationRoot config)
    	{
    		_config = config;
    	}
    
    	public async Task<IRestResponse> GetResponse(string configKey, object dtoObject)
    	{
    		//Get the URL from the config.json
    		var url = _config[configKey];
    
    		//Create rest client and rest request
    		var restClient = new RestClient(url);
    		var request = new RestRequest {Timeout = 30000, Method = Method.POST};
    
    		//Add header
    		request.AddHeader("Accept", "application/json");
    
    		//convert the dto object to json
    		var jsonObject = JsonConvert.SerializeObject(dtoObject.ToString(), Formatting.Indented);
    		request.AddParameter("application/json", jsonObject, ParameterType.RequestBody);
    
    		var taskCompletion = new TaskCompletionSource<IRestResponse>();
    
    		//Execute async
    		restClient.ExecuteAsync(request, r => taskCompletion.SetResult(r));
    		
    		//await the task to finish
    		var response = (RestResponse) await taskCompletion.Task;
    		
    		return response;
    	}
    }

    Thanks

    Sunday, July 2, 2017 2:16 PM

All replies

  • User1168443798 posted

    Hi MarcosBR,

    >> I am expecting that Service B send back some response: like OK or NOK

    I like this approach.

    In my option, I would not use too many status codes. The result of Web Api is right or wrong.

    I am implementing below way on my Web Api.

    1. Create a Response Model like below:

        public class WebApiResult
        {
            public string status { get; set; }
            public string message { get; set; }        
            //return customd data
            //public object data { get; set; }
        }

    2. API Controller

    [Produces("application/json", Type = typeof(MyModel))]
    public async Task<IActionResult> Post([FromBody]MyModel myModel)
    {
    	try
    	{
    		if (!ModelState.IsValid)
    		{
    			return Json(new WebApiResult { status = ApiStatus.NOK, message="Model is invalid" });
    		}
    
    		return Json(new WebApiResult { status = ApiStatus.OK, message="succeccfully" });
    	}
    	catch (Exception ex)
    	{		 
    		return Json(new WebApiResult { status = ApiStatus.NOK, message="ex message" });
    	}
    }

    3.You could check the response from the json and check the status of WebApiResult model.

    Best Regards,

    Edward

    Monday, July 3, 2017 2:45 AM
  • User-838515130 posted

    Thanks a lot for this!

    Monday, July 3, 2017 10:44 AM
  • User1404573039 posted

    Hi MarcosBR,

    If there is no other issue, I would suggest you mark the helpful reply as answer to close this thread.

    Regards,

    Tony

    Tuesday, July 4, 2017 6:29 AM