How To Make Laravel 8 REST API

How To Make Laravel 8 REST API

Avatar photoPosted by

Introduction:

Good day fellow dev, today I will be showing you how to make a Laravel 8 REST API. REST API is used for communication between client and server. REST stands for representational state transfer and API stand for application programming interface. REST API or also known as RESTful API is a type of API that uses the REST architectural style, an API is uses REST if it has this characteristics:

  • Client-Server – The communication between Client and Server.
  • Stateless – After the server completed a http request, no session information is retained on the server.
  • Cacheable – Response from the server can be cacheable or non cacheable.
  • Uniform Interface – This are the constraints that simplify things. The constraints are Identification of the resources, resource manipulation through representations, self-descriptive messages, hypermedia as the engine of application state.
  • Layered System – These are intermediaries between client and server like proxy servers, cache servers, etc.
  • Code on Demand(Optional) – This is optional, the ability of the server to send executable codes to the client like java applets or JavaScript code, etc.

Now you have a bit of insights about REST API. we will now proceed on creating this on Laravel 8.

Laravel has been one of the most popular PHP framework and widely used in web application development. It has widely chosen because of its features and benefits. We wont be talking about why we should Laravel but we will show you how to create a LARAVEL 8 REST API. This tutorial has been made for beginners or new to Laravel. Lets begin!

Step 1: Install Laravel 8 using Composer

Run this command on Terminal or CMD to install Laravel via composer:

composer create-project laravel/laravel laravel-8-rest-api

or via Laravel Installer:

laravel new laravel-8-rest-api

Step 2: Setup Database Configuration

Inside the project root folder open the file .env and put the configuration for database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your database name(laravel_8_rest_api)
DB_USERNAME=your database username(root)
DB_PASSWORD=your database password(root)

Step 3: Create Model with Migration

Model are class represents that represents a table on database.

Migration are like a version for your database.

Run this command on Terminal or CMD:

php artisan make:model Project --migration

After running this command you will find a file in this path “database/migrations” and update the code in that file.

<?php

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

class CreateProjectsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }

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

Run the migration by executing the migrate Artisan command:

php artisan migrate

Step 4: Create a API Resource Controller

Controller will be responsible on handling HTTP incoming request.

Run this command to create a API Resource Controller:

php artisan make:controller ProjectController --api

This command will generate a controller at “app/Http/Controllers/ProjectController.php”. It contains methods for each of the available resource operations. Open the file and insert these codes:

app/Http/Controllers/ProjectController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Project;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $projects = Project::get();

        return response()->json($projects);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $project = new Project();
        $project->name = $request->name;
        $project->description = $request->description;
        $project->save();

        return response()->json($project);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $project = Project::find($id);
        return response()->json($project);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $project = Project::find($id);
        $project->name = $request->name;
        $project->description = $request->description;
        $project->save();

        return response()->json($project);
    }

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

        return response()->json(['message' => 'Deleted']);
    }
}

Step 5: Add a API resource route

We will be using the route file routes/api.php since we are creating an API. The routes inside routes/api.php are stateless and uses the api middleware group.

When create a API resource route, you must use the apiResource method to exclude the route that represents create and edit html templates.

Now we register the API resource routes:

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProjectController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::apiResource('projects', ProjectController::class);

Step 6: Run the Laravel App

Run this command to start the Laravel App:

php artisan serve

After successfully running your app, open this URL in your browser:

http://localhost:8000

Test the API:

We will be using Postman for testing our API, but you can use you preferred tool.

POST Request – This request will create a new resource.

laravel 8 rest api post request Binaryboxtuts

GET Request – This request will retrieve all the resources.

laravel 8 rest api show all request Binaryboxtuts

GET Request (with id) – This request will retrieve a particular resource.

laravel 8 rest api show request Binaryboxtuts

PATCH Request or you can use the PUT Request – This request will update a resource.

laravel 8 rest api patch request Binaryboxtuts

DELETE Request – This request will delete a resource.

laravel 8 rest api delete request Binaryboxtuts