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 index function of ArticleController like this:

   /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::all();
        return $this->success($articles);
    }

   /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $article =  Article::find($id);
        if($article){
            return $this->success($article);
        }
        return $this->notFound('Article Not Found');
    }

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 function, 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.

Also Read: Store API – Creating REST API in Laravel(Part IV)

So, our ArticleController looks like:

<?php

namespace App\Http\Controllers;

use App\Article;

use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;

class ArticleController extends ApiController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::all();
        return $this->success($articles);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  use Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {
        try{
            $article  =  new Article();
            $article->title = $request->input('title');
            $article->body = $request->input('body');
            $article->save();

            $result['data'] = $article->toArray();
            $result['status'] = true;

        }catch(\Exception $e){
            $result['status'] = false;
            $result['message'] = 'Operation failed due to '. $e->getMessage();
        }
        
        if($result['status']){
            return $this->success($result['data']);
        }else{
            return $this->fail($result['message']);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $article =  Article::find($id);
        if($article){
            return $this->success($article);
        }
        return $this->notFound('Article Not Found');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  use Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ArticleRequest $request, $id)
    {
        try{
            $article  =  Article::find($id);
            if(!$article){
                return $this->notFound('Article not found !');
            }
            $input['title'] = $request->input('title');
            $input['body'] = $request->input('body');

            $article->update($input);

            $result['data'] = $article->toArray();
            $result['status'] = true;

        }catch(\Exception $e){
            dd($e);
            $result['status'] = false;
            $result['message'] = 'Operation failed due to '. $e->getMessage();
        }

        if($result['status']){
            return $this->success($result['data']);
        }else{
            return $this->fail($result['message']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

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

{
    "status": "success",
    "status_code": 200,
    "message": "OK",
    "data": {
        "id": 6,
        "title": "What is Laravel",
        "body": "Laravel is a php framework based in mvc arcitecture",
        "created_at": "2019-02-09 11:46:55",
        "updated_at": "2019-02-09 11:46:55"
    }
}
Screenshot

 

 

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

{
    "status": "success",
    "status_code": 200,
    "message": "OK",
    "data": [
        {
            "id": 6,
            "title": "What is Laravel",
            "body": "Laravel is a php framework based in mvc arcitecture",
            "created_at": "2019-02-09 11:46:55",
            "updated_at": "2019-02-09 11:46:55"
        },
        {
            "id": 7,
            "title": "What is Laravel",
            "body": "Laravel is a php framework based in mvc arcitecture",
            "created_at": "2019-02-09 11:47:21",
            "updated_at": "2019-02-09 11:47:21"
        },
        {
            "id": 8,
            "title": "Greetings",
            "body": "How are you man ?",
            "created_at": "2019-02-09 11:47:40",
            "updated_at": "2019-02-10 11:01:45"
        },
        {
            "id": 9,
            "title": "What is Laravel",
            "body": "Laravel is a php framework based in mvc arcitecture",
            "created_at": "2019-02-09 11:48:03",
            "updated_at": "2019-02-09 11:48:03"
        },
        {
            "id": 10,
            "title": "What is Laravel",
            "body": "Laravel is a php framework based in mvc arcitecture",
            "created_at": "2019-02-10 10:43:47",
            "updated_at": "2019-02-10 10:43:47"
        }
    ]
}
Screenshot

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

Tags :



share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback