How to create REST API with Laravel (no views)

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

RESTful APIs are the backbone of modern web applications, providing a way for various systems to communicate with each other. Laravel, a powerful PHP framework, makes building these APIs a breeze, emphasizing simplicity, elegance, and readability. In this tutorial, we’re going to go through the process of creating a RESTful API in Laravel without the need for traditional views.

Setting up the Environment

Before we begin, you’ll need to set up a Laravel environment. If you don’t have Laravel installed, you can do so by following the official Laravel documentation. Once you have Laravel installed, you can create a new project using the following command:

composer create-project --prefer-dist laravel/laravel laravel-rest-api

After creating your project, head into the project directory:

cd laravel-rest-api

Database Configuration

Once in your project directory, the next step is to configure the database. Open up the .env file in the root of your project and make the necessary changes to the database configuration options to suit your database settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_api
DB_USERNAME=root
DB_PASSWORD=

Don’t forget to create your database if it doesn’t already exist.

Creating the Model, Migration, and Controller

Laravel’s artisan command makes it super easy to generate the basic MVC architecture. For this tutorial, let’s imagine we’re creating an API for ‘Books’. Run the following command to create a model with an accompanying migration and controller:

php artisan make:model Book -m -c

This will create a Book model, a migration file for the books table, and a BookController.

Defining the Migration

Edit the migration file located at database/migrations and define the structure of the books table:

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('author');
        $table->timestamps();
    });
}

Run the migration with the following command:

php artisan migrate

Setting Routes

In Laravel, defining API routes is done in the routes/api.php file. Add the following to handle RESTful operations:

use App\Http\Controllers\BookController;

Route::apiResource('books', BookController::class);

Building the Controller

Edit the BookController to handle CRUD operations. Here’s an example method for fetching a list of books:

public function index()
{
    return Book::all();
}

And for creating a new book:

public function store(Request $request)
{
    $book = Book::create($request->all());
    return response()->json($book, 201);
}

Continue to flesh out the methods show(), update(), and destroy() for viewing a single book, updating a book and deleting a book, respectively.

Testing the API

To test our API, we can use tools like Postman or cURL. To fetch all books:

GET /api/books

To create a new book:

POST /api/books
{
    "title": "My New Book",
    "author": "Author Name"
}

Be sure your headers include Content-Type: application/json when making POST requests.

Securing the API

Security is paramount when creating APIs. Laravel offers several ways to secure your API. You can use token-based authentication provided by Laravel Sanctum or opt for Laravel Passport which provides a full OAuth2 server implementation.

See also:

Error Handling and Responses

Laravel provides powerful tools for error handling and response formatting. For instance, you should always return appropriate HTTP status codes. Exceptions can be handled within the render method of the App\Exceptions\Handler class.

See also:

Advanced Concepts

As you advance, you might consider using API Resources to transform your models into JSON, implementing middleware for cross-origin resource sharing (CORS) and rate limiting, or using Laravel’s events and listeners to react to API events.

See also:

Conclusion

In this tutorial, you’ve seen how to create a RESTful API using Laravel without views. We’ve gone from initial setup, through creating routes, to securing and testing our API. This should provide a solid foundation for building and scaling your APIs in Laravel.