Code for consuming API

Introduction

            
            public async Task Get()
                {
                    try
                    {
                        using (var httpClient = new HttpClient())
                        {
                            using (var response = await httpClient.GetAsync("http://localhost:81/myapi/api/api.php"))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    string apiResponse = await response.Content.ReadAsStringAsync();
                                    ApiResponse apiResult = JsonConvert.DeserializeObject(apiResponse);
                                    List reservationList = apiResult.Data;
                                    return View(reservationList);
                                }
                                else
                                {
                                    // Handle the case where the API call was not successful
                                    // You might want to log the response status or handle it accordingly
                                    ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
                                    return View(new List()); // return an empty list or handle it as per your requirement
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Handle any exceptions that occur during the API call
                        // Log the exception details or handle the error appropriately
                        ModelState.AddModelError(string.Empty, "Exception occurred while retrieving data from server.");
                        return View(new List()); // return an empty list or handle it as per your requirement
                    }
                }
        
    

Summary

APIs, or application programming interfaces, are crucial for interoperability across many technologies in the field of web development. Systems may communicate and share data with ease thanks to APIs, regardless of the framework you're using—Java,.NET, Angular, React, or another one.

This example shows you how to use the HttpClient in.NET Core to consume an API. You can use this class to handle HTTP replies from a defined URI and send HTTP queries. In this case, we are concentrating on submitting an asynchronous GET request to a specified API endpoint. The implementation ensures strong integration with external APIs in a web application environment by including ways to handle both successful and unsuccessful answers.

Explanation of .NET Core API Consumption Code

Method Declaration:

public async Task<IActionResult> Get(): This declares a public asynchronous method named Get that returns an IActionResult. In ASP.NET Core, methods like these typically handle HTTP requests.

Try-Catch Block:

The entire method is enclosed in a try-catch block to handle exceptions that might occur during the API call.

HTTP Client Initialization:

using (var httpClient = new HttpClient()): This creates an instance of HttpClient, which is used to send HTTP requests and receive HTTP responses from a specified URI.

Sending GET Request:

using (var response = await httpClient.GetAsync("http://localhost:81/myapi/api/api.php")): This line sends an asynchronous GET request to the specified URI (http://localhost:81/myapi/api/api.php). The await keyword ensures that the method asynchronously waits for the response.

Handling API Response:

if (response.IsSuccessStatusCode): Checks if the HTTP response was successful (status code in the 200-299 range).

If successful:

If not successful:

Exception Handling:

catch (Exception ex): Catches any exceptions that occur during the execution of the try block.