Logo

dev-resources.site

for different kinds of informations.

Building a RESTful API with Laravel 11, A Complete Guide

Published at
9/8/2024
Categories
laravel
api
sqlite
sanctum
Author
hamzasehouli
Categories
4 categories in total
laravel
open
api
open
sqlite
open
sanctum
open
Author
12 person written this
hamzasehouli
open
Building a RESTful API with Laravel 11, A Complete Guide

Laravel is a popular PHP framework known for its simplicity and power. It allows developers to create robust and scalable backend services. 
In this guide, we will walk through the process of creating, securing, and documenting a RESTful API using Laravel.

Step 1: Install Laravel

Before we begin, make sure you have Laravel installed on your local machine. To create a new Laravel project, run the following command:

composer create-project laravel/laravel laravel-restful-api

Enter fullscreen mode Exit fullscreen mode

Go to the project directory:

cd laravel-restful-api

Enter fullscreen mode Exit fullscreen mode

Step 2: Database configuration

Laravel supports many databases. I use Sqlite for this demo, but you can choose another. To configure yours, go to the .env file and set your database credentials.

DB_CONNECTION=sqlite
DB_DATABASE=../database/database.sqlite
Enter fullscreen mode Exit fullscreen mode

SQLite databases are in one file on your filesystem. You can create a new SQLite database with the touch command in your terminal or manually:

 

touch database/database.sqlite

Enter fullscreen mode Exit fullscreen mode

In Windows:

echo > database/database.sqlite

Enter fullscreen mode Exit fullscreen mode

Step 3: Creating Models, Migrations, and Controllers

To build a simple API for managing blog posts, start by creating a migration, model, and controller for Post. You may need another controller for authentication AuthController, but you can write the authentication logic in the UserController.

php artisan make:model Post -m -c --api
Enter fullscreen mode Exit fullscreen mode

The - api flag generates an API-specific controller without boilerplate methods for rendering views.

This single line of code will create the following routes:

GET /api/posts – List all posts
GET /api/posts/{id} – Get a specific post
POST /api/posts – Create a new post
PUT /api/posts/{id} – Update a post
DELETE /api/posts/{id} – Delete a post
Enter fullscreen mode Exit fullscreen mode

This will create a model (Post.php) and a migration file in the database/migrations folder. Open the migration file and define the schema for the posts table.

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('author');
    $table->mediumText('excerpt');
    $table->longText('text');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

In the Post model, add the fillable property:

protected $fillable = ['title', 'author', 'excerpt', 'text'];
Enter fullscreen mode Exit fullscreen mode

Now, run the migration:

php artisan migrate

Enter fullscreen mode Exit fullscreen mode

Step 4: Defining Routes

Laravel lets you define API routes in routes/api.php. These routes are prefixed with /api. Define the routes for Post:
If you don't see the api.php file in the routes folder, you can either create it through the command line interface or just manually.
We've added the posts API resources to the sanctum middleware so we can check and filter HTTP requests coming into your app. To do this, you need to have the sanctum package installed. If you don't have it, just run this command to install it:

php artisan install:api

Enter fullscreen mode Exit fullscreen mode

Next, you'll want to add the path to the api.php file to the app.php file in the bootstrap folder. Then, map it to the api name, as shown in the code below.

Step 5: Implementing the API Logic in the AuthController

I like to keep things organized and separated based on specific roles and functions, so I will create another AuthController that will handle the authentication logic.

php artisan make:controller AuthController

Enter fullscreen mode Exit fullscreen mode

Image description
Image description
We also need to add HasApiTokens trait to the User model

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Let's add index, store, and show methods to the PostController to handle posts.

Image description
To test the newly create API that manages blog posts, I use Postman, which is an API platform for building and using APIs:
To log in, just use the URL below and add your email address and a valid password.

http://localhost:8000/api/login

Enter fullscreen mode Exit fullscreen mode

After a successful log in attempt, you will a json response as show below:

 

{
    "0": {
        "ok": true,
        "user": {
            "id": 4,
            "name": "Hamza Sehouli",
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": "2024-09-07T21:51:50.000000Z",
            "updated_at": "2024-09-07T21:51:50.000000Z"
        },
        "token": "5|8vamsAP4WPkbctrecPnXymRYpkaiQU4AkBW2AwQq3f30e7d4"
    },
    "status": 200
}
Enter fullscreen mode Exit fullscreen mode

As we added the API resources for posts to the sanctum:auth middleware in the api.php route file, we need to include a bearer token in the header to access the posts data.

Image description

For instance, to retrieve all posts using a GET request, we simply enter the URL below:

http://localhost:8000/api/posts

Enter fullscreen mode Exit fullscreen mode

Bottom line 

Laravel makes it easy to handle authentication with built-in systems and tools like Sanctum. Even when you're building authentication manually, Laravel's Auth facade, and middleware give you powerful tools to streamline the process of logging in, signing up.

sqlite Article's
30 articles in total
Favicon
Android SQLite Crud Tutorial
Favicon
🚀 Building a User Management API with FastAPI and SQLite
Favicon
How to Use SQLite in Vue 3: Complete Guide to Offline-First Web Apps
Favicon
Building a Simple SQLite Library Manager in Python
Favicon
MySQL vs SQLite أيهما أفضل ؟
Favicon
How to setup Ghost in a VPS using Docker, Mailgun and SQLite
Favicon
Java JDBC + IntelliJ + SQLite - A Beginner's Walkthrough
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
How to Query CSV Files with SQLite
Favicon
Deploy FastAPI application with SQLite on Fly.io
Favicon
How to import excel into sqlite only 1 step
Favicon
PostgreSQL vs. SQLite: read & write in multithreaded environment
Favicon
PostgreSQL vs. SQLite: 멀티스레드 환경에서의 읽기-쓰기
Favicon
Sometimes it's the little things
Favicon
Tauri 2.0 - Sqlite DB - React
Favicon
SQLite Database Recovery
Favicon
Streamlining Your Rails 8 App: Migrating from Postgres to SQLite
Favicon
I still prefer SQLite for little things you know.
Favicon
How to Build Lightweight GraphRAG with SQLite
Favicon
Can You Create a Product That Makes Money with Wasm?
Favicon
Building a cache in Python
Favicon
Building a RESTful API with Laravel 11, A Complete Guide
Favicon
In-Memory Database with SQLite
Favicon
Build your own SQLite, Part 2: Scanning large tables
Favicon
Fundamentos para Web APIs com .NET: Uma Introdução ao Essencial com Entity Framework
Favicon
Multitenant Database Schemas
Favicon
Use SQLite as a Celery broker in Django
Favicon
Build your own SQLite, Part 1: Listing tables
Favicon
Hosting a simple Laravel application using Turso on Laravel Forge
Favicon
Introducing vectorlite: A Fast and Tunable Vector Search Extension for SQLite

Featured ones: