Creating A Basic REST API in Laravel 9
Tags: api, laravel, tutorial
Published: 2022-11-23 14:07:37


In this tutorial, I am going to take you through the basics in building a REST API in Laravel. But before that lets take a quick glance into what a REST API is.

What is REST API?

A REST API, commonly referred to as a RESTful API, is a web API that complies with the restrictions of the REST architectural style and enables communication with RESTful web services. Computer scientist Roy Fielding came up with the acronym REST, which stands for representational state transfer.

[More on REST APIs](https://www.redhat.com/en/topics/api/what-is-a-rest-api)

Let get started.

### Create a new `Laravel project`
```http
composer create-project laravel/laravel basic_laravel_api
```
or using `Laravel Installer`
```http
laravel new basic_laravel_api
```
and move into the directory
```http
cd basic_laravel_api
```
### Create a model and migration
```http
php artisan make:model Post -m
```

### Update and migrate your database
```http
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=basic_laravel_api
DB_USERNAME=root
DB_PASSWORD=
```
#### Post table update
```http
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

```
Then run your migrations
```http
php artisan migrate
```

### Create and Update your Controller
```http
php artisan make:controller Api\\PostController --model=Post
```

#### Api Controller
```http
<?php

namespace App\Http\Controllers\Api;

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

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

        return response()->json([
            'status' => true,
            'post' => $posts
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $post = Post::create(request()->all());

        return response()->json([
            'stauts' => true,
            'post' => $post
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        $post = Post::find($post)->first();

        return response()->json([
            'status' => true,
            'post' => $post
        ]);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $post->update(request()->all());
        return response()->json([
            'status' => true,
            'post' => $post
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();

        return response()->json([
            'status' => true,
        ]);
    }
}

```

### Define your routes
open routes/api.php
```http
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\PostController;

Route::apiResource('v1/posts', PostController::class);

```

### Start Laravel Server
```http
php artisan serve
```

## Preview using Postman
### `GET` all Post
![GET all Post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3kj2hb4m6o2u5iejvcbu.png)
### Create a Post. `POST`
![Create(POST) a Post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/je04b47b0sr0c2evazkq.png)
### `GET` a specific post
![GET a single post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zrwrti6vo89m2vlxjhq.png)
### Update a post. `PUT/PATCH`
![Update a post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ocj9ersp1xtb70zgcqx.png)
#### `DELETE` a post
![Delete a post](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l1reakmt0erumg5xrv0t.png)