Contents
Introduction:
Good day fellow dev, today I will be showing you how to make a Laravel 9 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 9.
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 9 REST API. This tutorial has been made for beginners or new to Laravel. Lets begin!
Step 1: Install Laravel 9 using Composer
Run this command on Terminal or CMD to install Laravel via composer:
composer create-project laravel/laravel laravel-9-rest-api
or via Laravel Installer:
laravel new laravel-9-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
Model are class represents 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 on 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 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.
GET Request – This request will retrieve all the resources.
GET Request (with id) – This request will retrieve a particular resource.
PATCH Request or you can use the PUT Request – This request will update a resource.
DELETE Request – This request will delete a resource.