CALL API in Laravel 8

Tram Ho

Call API through real life examples. Is the regular work of web developers, especially Backend programmers!

In laravel, Intern or Fresher usually write Function call api in Controller. As for junior & senior, they also write in Command, Service. In this article, I will share how to call api in Controller.

Let’s get started together!

First I need the apiUrl, in the Api project will usually come from the Backend programmer. Along with that, the backend programmer will tell you what the api needs to input so that the API can return data, it has the form like the Url usually: ” https://abc.def.xxx/{ email}/{phone}

In the above API Url, we see that there is a path and two variables enclosed in curly braces { } are email and phone. That is, this API wants to call it, we have to pass two variables email and phone to the url. Depending on the request of the backend, the data is transmitted in different POST or GET methods. Commonly used is the POST method. In this example: $apiUrl has the following form: backend requires Post email or phone attached to get user information in the system!

and I will need the $postinput variable as follows:

Next I need the $header variable as follows:

Almost done, now will get the data back by connecting the 3 components above together as follows:

When I call the API, the server on the other side will return me the connection status: there are usually 3 common states: 200 – 404 – 500. In which status 200 is a successful connection, 404 vs 500 is an error. difference. I need to check that status by checking the status code through the command:

When the status code = 200 means that the API connection is successful, we will get the data from it through the following statement:

The data we receive is usually an array, our next job is to pass that array through the view and display the data on the view.

Above is my share about Post to call api, because this is my first post, if it is difficult to understand, please give me your opinion.

My next article will share api calls that do not need to pass input, please pay attention to follow! Thank you so much! Here is my sample code:

$apiURL = ‘ https://abcxyz.vv.vn/v1/user/list ‘;

Good luck

Share the news now

Source : Viblo