How To Make Laravel 10 REST API

How To Make Laravel 10 REST API

Avatar photoPosted by

Introduction:

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

  • Client-Server – The communication between Client and Server.
  • Stateless – After the server completes an HTTP request, no session information is retained on the server.
  • Cacheable – Response from the server can be cacheable or non-cacheable.
  • Uniform Interface – These are the constraints that simplify things. The constraints are Identification of the resources, resource manipulation through representations, self-descriptive messages, and hypermedia as the engine of the 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 insight into REST API. we will now proceed on creating this on Laravel 9.

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

Step 1: Install Laravel 10 using Composer

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

composer create-project laravel/laravel:^10.0 laravel-10-rest-api

or via Laravel Installer:

laravel new laravel-10-rest-api

Step 2: Setup Database Configuration

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

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

Step 3: Create a Model with Migration

Models are class that represents a table on a database.

Migration is like a version of 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 an API Resource Controller

The controller will be responsible for handling HTTP incoming requests.

Run this command to create an 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 an 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 use the API middleware group.

When creating 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