How to create api with laravel 5

Hello World, Welcome to my website. Today I will discuss how to create API with laravel 5. Laravel provides a very efficient way to create API with its resource controller which are already structured around REST verbs and patterns. In this tutorial, we will create a simple example to better understand APIs.

I am using laravel 5.8

I have divided this tutorial into the following parts.

  • Create Resource Controller
  • Create Modal
  • Access Data via Resource Controller
  • API Routing
  • Test API in Postman


Create Resource Controller

The resource controller is similar to normal controller but the main difference is the resource controller exclude the create() and edit() method. We do not need these methods in APIs. Let’s create the resource controller with the following artisan command.

php artisan make:controller Api\PostController --api

The above command will create the PostController file in the app\Http\Controllers\Api folder. You can see that this controller has just index, store, show, update and destroy methods. Next, we create a modal for this example.


Create Modal

In this step, We will create post modal for this example so that we can access and save post data in the database. The following code will create post modal and migration.

php artisan make:modal Post -m

For a detailed study of migration in laravel, please follow this article.

Add some columns in the migration file and migrate with the following command.

php artisan migrate

This will create posts table in the database.

Please add the fillable property in this Model class. for example

protected $fillable=['title','body'];

Access data via Resource Controller

In this step, We will access post modal data in the Resource controller with Laravel Eloquent ORM. Please replace the following code with the previous code of PostController.

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Post;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Post::paginate(10);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        return Post::create([
            'title'=>$request->title,
            'body'=>$request->body
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return Post::FindOrFail($id);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $post=Post::FindOrFail($id);
        $post->update([
            'title'=>$request->title,
            'body'=>$request->body
        ]);
        return $post;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Post::FindOrFail($id)->delete();
    }
}

When we run our api then this code will return JSON data to the client.


API Routing

Add the following code in routes/api/api.php file.

Route::apiResource("posts",'Api\PostController');
// Url Structure
http://localhost/laravel-project/public/api/posts

This route will work as following REST API Structure.

Following is Common REST API endpoint structures.
//	All Posts
-	GET api/posts
[
	{
		id:1,
		name:'Fluffy'
	},
	{
		id:2,
		name:'Killer'
	}
]
----------
//	Single Post
-	Get api/posts/1
	{
		id:1,
		name:'Fluffy'
	}
----------
//	Delete Post
-	api/posts/1

//	Create Post
-	POST api/posts
	{
		name:'post 1'
	}
----------
//	Update Post
//	PATCH api/posts/1
	{
		name:'post 1'
	}

Test API in PostMan Client

We have created our API, Now we will test it on the postman. A PostMan is a tool that provides GUI to send the request to the server and read the response. Please download the postman app according to your operating system.

We will perform the following tasks in the postman.

  • Fetching data
  • Adding data or sending data to the server
  • Updating data
  • Deleting data

Open this postman app and select request type and add API url. Following is the example screenshot.

postman-request

In the above screenshot, you can see that we are fetching all posts with GET request.

Leave a Reply