EN ES
Home > Web development > Laravel Tutorials > How to create RESTful API with Laravel

How to create RESTful API with Laravel

Diego Cortés
Diego Cortés
September 11, 2024
How to create RESTful API with Laravel

Laravel is one of the most popular and widely used PHP frameworks today, thanks to its ease of use and extensive developer community. In this article, we will learn how to create a basic RESTful API using Laravel. This article is structured to guide you through the necessary steps

What is a RESTful API?

A RESTful API is a set of functions that allows communication between different applications through HTTP. REST (Representational State Transfer) is an architectural style that uses HTTP verbs such as GET, POST, PUT, and DELETE to perform operations on resources.

Prerequisites

Before you begin, make sure you have the following installed:

  • PHP: The latest recommended version (at least PHP 7.3).
  • Composer: Dependency management tool for PHP.
  • Laravel: The PHP framework we will use to develop our API.

Installing Laravel

To create a new Laravel project, open your terminal and run the following command:

composer create-project --prefer-dist laravel/laravel project-name

Replace project-name with the desired name for your project. After executing the command, navigate to the project folder:

cd project-name

Setting Up the Database

Creating the Database

Make sure you have a running database server, such as MySQL. Create a new database for your API.

Configuration in the .env File

Open the .env file in the root of your project and set the following parameters:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

Replace database_name, your_username, and your_password with the corresponding values.

Creating a Model and Migrations

Generating a Model

In Laravel, a model represents a table in the database. To generate a model, run the following command in the terminal:

php artisan make:model ModelName -m

Replace ModelName with the name of your model, for example, Product. Using -m will also generate a migration for the corresponding table.

Editing the Migration

Go to the database/migrations folder and edit the generated migration. Add the necessary columns. For example, if you are creating a product model, you might have:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Running the Migration

To create the table in the database, run:

php artisan migrate

Configuring API Routes

Laravel provides a clear structure for defining your API routes. Open the routes/api.php file and define your routes. For example, for a product model:

use App\Http\Controllers\ProductController;

Route::get('/products', [ProductController::class, 'index']);
Route::post('/products', [ProductController::class, 'store']);
Route::get('/products/{id}', [ProductController::class, 'show']);
Route::put('/products/{id}', [ProductController::class, 'update']);
Route::delete('/products/{id}', [ProductController::class, 'destroy']);

Creating a Controller

To handle the logic behind your routes, you will need a controller. Run the following command:

php artisan make:controller ProductController --resource

This will generate a controller with predefined methods for CRUD operations. Open app/Http/Controllers/ProductController.php and add the logic for each method:

Example Methods in the Controller

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

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

public function show($id)
{
    return Product::findOrFail($id);
}

public function update(Request $request, $id)
{
    $product = Product::findOrFail($id);
    $product->update($request->all());
    return response()->json($product, 200);
}

public function destroy($id)
{
    Product::destroy($id);
    return response()->json(null, 204);
}

Testing the API

Using Postman

Postman is a useful tool for testing APIs. You can make GET, POST, PUT, and DELETE requests to the routes you have defined.

  1. GET: http://localhost:8000/api/products to get all products.
  2. POST: http://localhost:8000/api/products to create a new product. Make sure to send the data in JSON format.
  3. GET with id: http://localhost:8000/api/products/1 to get a specific product.
  4. PUT: http://localhost:8000/api/products/1 to update a specific product.
  5. DELETE: http://localhost:8000/api/products/1 to delete a specific product.

Conclusion

In this article, we have covered the necessary steps to create a simple RESTful API using Laravel. From installing the framework to creating a model, migrations, and controllers, you are now equipped to build and expand your own APIs.

Additional Resources

With this guide, you can begin exploring API development effectively and efficiently using Laravel. Good luck on your programming adventure!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 24.58 ms