API Development with Laravel 10

API Development with Laravel 10 - A Comprehensive Guide

“Hello, everyone! Welcome to our tutorial on ‘API Development with Laravel.’

Now, let’s discuss API development and its importance. APIs, or Application Programming Interfaces, are the connectors that allow software systems to communicate and share information with each other. APIs have become a crucial component of modern web and mobile applications, and mastering API development is an essential skill for any developer.

The goal of this tutorial is to guide you step by step through the process of creating a functional and secure API using Laravel. By the end of this tutorial, you will be able to create, configure, and test your own APIs with Laravel.

Are you excited? Because I sure am! So, without further ado, let’s dive in and get started.”

Let’s go through an example of creating a simple API using Laravel 10, where we’ll build a simple CRUD (Create, Read, Update, Delete) API for a ‘Product’ resource.

1. Installation & Project Setup

First, we need to create a new Laravel project. Open your terminal and navigate to your preferred directory, then run:

composer create-project --prefer-dist laravel/laravel:^10.0 api_demo

2. Setup a MySQL Database

In your .env file, update your database credentials:

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

3. Create Model, Migration, and Controller

In Laravel, we can create a model with a migration file and a controller at the same time using artisan command. Run the following command in your terminal:

php artisan make:model Product -mc

This will create a model ‘Product’, a migration file for creating the ‘products’ table, and a controller ‘ProductController’.

You need to specify either a fillable or guarded property on your model to allow or deny mass assignment on model properties.

Here’s how you can add a $fillable property to the ‘Product’ model to allow mass assignment on ‘name’, ‘description’, and ‘price’ fields:

class Product extends Model
{
    use HasFactory;


   protected $fillable = [
  'name', 'description', 'price'
   ];
}

4. Create and Run Migrations

Open the ‘create_products_table’ migration file in your ‘database/migrations’ directory and update the up method:

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

Save the file and run the migration using the command:

php artisan migrate

5. Update the Controller for CRUD Operations

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
public function index()
{
    return Product::all();
}

public function store(Request $request)
{
     $validated = $request->validate([
    'name' => 'required|max:255',
    'description' => 'required',
    'price' => 'required|numeric',
]);

$product = Product::create($validated);

    return response()->json($product, 201);
}
public function show(Product $product)
{
   return response()->json($product, 200);
}

public function update(Request $request, Product $product)
{
     $validated = $request->validate([
    'name' => 'sometimes|max:255',
    'description' => 'sometimes',
    'price' => 'sometimes|numeric',
]);

    $product->update($validated);

    return response()->json($product, 200);
}

public function destroy(Product $product)
{
    $product->delete();
    return response('Deleted', 200);
}
}

6. Setup Routes

In ‘routes/api.php’, add the following line:

use App\Http\Controllers\ProductController;

Route::apiResource('products', ProductController::class);

Now, you have a working CRUD API for a ‘Product’ resource. You can test the API using a tool like Postman or cURL. You can create, retrieve, update, and delete products.

In the provided example, we’ve set up a simple CRUD API for ‘Product’ resource. Given that you’re running your application locally, you’ll be able to use the following endpoints with your Laravel API:

  1. List all products (GET request): http://127.0.0.1:8000/api/products
  2. Create a new product (POST request): http://127.0.0.1:8000/api/products
    • In Postman, choose POST as the request method.
    • The body of the request should be a JSON object that includes ‘name’, ‘description’ and ‘price’, like so:
    {
      "name": "Product Name",
      "description": "Product Description",
      "price": 99.99
    }

3. Show a single product (GET request): http://127.0.0.1:8000/api/products/{product}

    • Replace {product} with the ID of the product you want to retrieve.
    • e.g http://127.0.0.1:8000/api/products/1

4. Update a product (PUT or PATCH request): http://127.0.0.1:8000/api/products/{product}

      • Replace {product} with the ID of the product you want to update.
      • The body of the request should be a JSON object that includes the fields you want to update, for example:
           {
             "name": "New Product Name",
              "price": 149.99
           }

        5. Delete a product (DELETE request): http://127.0.0.1:8000/api/products/{product}

        • Replace {product} with the ID of the product, you want to delete.

Setting Authentication In Our App

Implementing authentication in an API context usually means implementing a token-based authentication system, because unlike in a web context, you don’t have sessions in an API context. Laravel provides several ways to handle API authentication, such as Laravel Sanctum, Passport, or JWT (JSON Web Token) authentication with third-party packages. You could add middleware to your routes that ensure the user is authenticated before allowing them access to certain routes. For instance:

Route::middleware('auth:sanctum')->group(function () {
   Route::apiResource('products', ProductController::class);
});

Laravel determines if a request is an AJAX request by checking if the X-Requested-With header is set to XMLHttpRequest.

In Postman, ensure that you are setting the header X-Requested-With to XMLHttpRequest. You can do this by going to the “Headers” tab in Postman and adding a new key-value pair:

X-Requested-With: XMLHttpRequest.

This should ensure that Laravel treats the request as an AJAX request and returns validation error messages in JSON format, which can be easily read in Postman.

Using Laravel Sanctum

Route::post('/sanctum/token', function (Request $request) {
     $request->validate([
    'email' => 'required|email',
    'password' => 'required'
]);


$user = User::where('email', $request->email)->first();


if (! $user || ! Hash::check($request->password, $user->password)) {
   throw ValidationException::withMessages([
   'email' => ['The provided credentials are incorrect.'],
   ]);
}


return $user->createToken($request->device_name)->plainTextToken;
});

So, you will make a POST request to http://127.0.0.1:8000/api/sanctum/token (replace 127.0.0.1:8000 with your server’s actual address if it’s different).

In the body of the request, you will provide the email, password, and device_name as JSON. For example:

{
    "email": "user@example.com",
    "password": "your_password",
    "device_name": "your_device_name"
}

This will authenticate the user, and if the credentials are valid, return a plain text API token.

Once you have the token, you will include it in the header of subsequent requests to authenticate them. The header key is Authorization and the value is Bearer your_token, replacing your_token with the actual token you received.

Example:

  1. Open a new tab for a new request in Postman.
  2. Enter your API endpoint URL in the address bar (e.g., http://127.0.0.1:8000/api/products).
  3. Set the HTTP method to GET, POST, PUT, or DELETE, depending on what you want to do.
  4. Click on the Headers tab below the address bar.
  5. Under Key, type Authorization. Under Value, type Bearer , followed by your token. It should look like this: Bearer your_token. Make sure to replace your_token with the actual token string you received.
  6. Now, send your request. With the Bearer token in the header, your request should be authenticated.

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published. Required fields are marked *