Fetch API – Creating REST API in Laravel(Part VI)

Fetch Api is an api end point for fetcing records from the database. We are using article as our entity so it will be article fetch api. We will create separate api for fetching single article and all articles. In previous article, we have created an update api to update record in database. We have also created store api to store articles in the database. We have already created database structure, eloquent model, routes, controller functions as well. Now, we will add all necessary logic to index and show functions in controller to create single article fetch api and all articles fetch api.

We have already added fetch api route in api.php file, you can see this post for reference.

Let’s add the logic in the store function of ArticleController like this:

In the index function, we have collected all the articles and returned json response with success function. Even if no article exist, we will return success function.

In show funtion, we have searched the article for given id. If article exists then we will return success function along with article otherwise we will return not found response.

Store API – Creating REST API in Laravel(Part IV)

So, our ArticleController looks like:

At first, we have imported the Article model. Then, we will extend our controller from ApiController so that we can send response based on processing of request. Finally, we have added logic to fetch article or articles in the show or index function respectively.

We have used success return in index function which will return articles with HTTP_OK status. In the show function, If requested article is not found then we will return not found with HTTP_NOT_FOUND status. If article exists, we will return success with HTTP_OK status.

Test using Postman

I’m using ubantu local server. I’ve hosted my application at localhost:8000. Now, open postman then test the following api.

Single Article Fetch

1.Set method type to GET

2. Set route to http://localhost:8000/api/articles/6, here 6 is the id of article in my case. It may differ for your case.

3. Send the request you will get output like this

Screenshot

Single article fetch api

All Article Fetch

1.Set method type to GET

2. Set route to http://localhost:8000/api/articles

3. Send the request you will get output like this

Screenshot

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *