Tuesday, October 11, 2022

Handling Response of REST API

Let's say we need to use some REST api in our application. This api give an response object like below:

  • Object:
    • isSuccess
    • message
    • result
For example, we use a blogger service for our blog, and let's say this service provides some features like recent posts, statistics of post, etc. This features has fields that defined by publisher of the api. We should know these fields of the features, so we can implement this our project. We need to create a response class and response objects according to the fields of the features:
public class Response<T>
{
    public bool isSuccess { get; set; }
    public string message { get; set; }
    public T result { get; set; }
}

// we created response object classes according to the api
public class RecentPostResponse 
{
    public int postId { get; set; }
    public string title { get; set;}
    public string author { get; set; }
    public string publishedDate { get; set; }
}

public class PostStatisticResponse
{
    public int postId { get; set; }
    public int viewCounter { get; set; }
}
We have to create request method to use the api. Probably, the publisher will give an username and password or token.
private Response<T> SendRequest<T>()
{
	...
    
    string responseContent = ...
    
    Response<T> response = Json.DeserializeObject<Response<T>>(responseContent);
    
    return response;
}
I can use the api. I want to get recent post list via the api:
...

Response<List<RecentPostResponse>> response = SendRequest<List<RecentPostResponse>>();

List<RecentPostResponse> recentPostList = response.result;

...
That's how we can handle it.😟

No comments:

Post a Comment