Skip to main content
Laravel Basics Tutorial
CHAPTER 15 Beginner

Building REST APIs with Laravel

Updated: May 14, 2026
30 min read

# CHAPTER 15

Building REST APIs with Laravel

1. Introduction

If you are building an iOS app, an Android app, or a React Single Page Application, those frontends cannot read Blade HTML files. They need raw data. A REST API acts as the delivery mechanism, sending database records packaged in a universal text format called JSON. Laravel is one of the most powerful tools in the world for building APIs. In this chapter, we will decouple our backend from our views and learn how to serve pure JSON data.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define routes specifically for APIs.
  • Return JSON responses and HTTP Status Codes.
  • Understand API Controllers and Resource Routing.
  • Implement basic API Token Authentication (Sanctum).

3. Beginner-Friendly Explanation

Imagine a restaurant. When a customer dines in (a Web Browser), the chef (Controller) puts the food on a beautiful ceramic plate (a Blade HTML View) and serves it. When an UberEats driver arrives (a Mobile App), they don't want the ceramic plate; they would drop it in the car! The chef puts the raw food into a standardized, square cardboard box (JSON) and hands it to the driver. The driver takes it to the customer, who plates it themselves. APIs are the takeout window. They serve raw JSON data, allowing frontend systems (like iPhones) to build their own user interfaces.

4. The API Routes File

Laravel specifically separates Web routes and API routes. Open routes/api.php. Any route defined here automatically has /api prefixed to its URL. It also strips away web middleware (like session cookies and CSRF protection) because APIs are designed to be "stateless."
php
1234
use App\Http\Controllers\Api\ProductController;

// URL will be: site.com/api/products
Route::get('/products', [ProductController::class, 'index']);

5. Returning JSON from a Controller

When building an API, you do not use return view(). You return an Array, an Eloquent Collection, or a JSON response. Laravel automatically converts arrays and objects to JSON strings!

app/Http/Controllers/Api/ProductController.php

php
12345678910111213141516171819202122232425262728293031323334353637
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        // Fetch all products
        $products = Product::all();

        // Laravel automatically converts this Eloquent Collection to JSON!
        return response()->json([
            &#039;status' => 'success',
            &#039;data' => $products
        ], 200); // 200 is the HTTP status code for "OK"
    }

    public function show($id)
    {
        $product = Product::find($id);

        if (!$product) {
            // Return a 404 error if the product doesn't exist
            return response()->json([
                &#039;status' => 'error',
                &#039;message' => 'Product not found'
            ], 404);
        }

        return response()->json([
            &#039;status' => 'success',
            &#039;data' => $product
        ], 200);
    }
}

*If you visit site.com/api/products in your browser, you will see a raw wall of text formatting like {"status":"success", "data":[{"id":1, "name":"Laptop"}]}.*

6. Handling POST Requests (Creating Data via API)

APIs don't use Blade forms with @csrf. Mobile apps send raw JSON payloads. Laravel's Request object reads this JSON automatically.
php
123456789101112131415161718
public function store(Request $request)
{
    // Validate the incoming JSON payload
    $validated = $request->validate([
        &#039;name' => 'required|string|max:255',
        &#039;price' => 'required|numeric'
    ]);

    // Create the product
    $product = Product::create($validated);

    // 201 is the HTTP status code for "Created"
    return response()->json([
        &#039;status' => 'success',
        &#039;message' => 'Product created',
        &#039;data' => $product
    ], 201); 
}

7. API Authentication (Laravel Sanctum)

Because APIs do not use browser Cookies, how does a mobile app prove it is logged in? It uses a Token (a long, secret password like 1|xyz789ABC). Laravel uses a package called Sanctum to manage this. When a user logs in via the mobile app, Laravel generates a Token and sends it back. The mobile app must attach this Token as a "Bearer Token" in the HTTP Header of every subsequent request.

Protecting the API Route:

php
1234
// Only mobile apps that send a valid Token can access this route!
Route::middleware(&#039;auth:sanctum')->get('/user/profile', function (Request $request) {
    return $request->user(); // Returns the logged-in user's JSON data
});

8. Testing APIs with Postman

You cannot test POST, PUT, or DELETE API requests easily in a web browser. Professional API developers use a free tool called Postman. You type your API URL into Postman, craft a fake JSON payload, and click "Send" to see how your Laravel API responds.

9. Best Practices

  • API Resources: As your app grows, you don't want to expose every column of your database (like is_admin or password_hash) in the JSON response. Laravel provides "API Resources" (php artisan make:resource ProductResource) that allow you to explicitly define exactly which fields are sent in the JSON box.

10. Common Mistakes

  • Returning HTML Errors in an API: If a database query fails in an API, Laravel's default behavior is to render a beautiful HTML error page. However, a mobile app expects JSON, so the HTML causes the mobile app to crash. You must ensure your API routes always return errors explicitly formatted as JSON.

11. Exercises

  1. 1. Explain the difference between routes/web.php and routes/api.php regarding what type of responses they are expected to generate.

12. Coding Challenges

  • Challenge: Write an API Controller method called destroy($id). It should find a product by its ID, delete it, and return a JSON response with a success message and an HTTP Status Code of 200.

13. MCQs with Answers

Question 1

When building a REST API in Laravel, what data format is almost universally returned to the client (such as a mobile app)?

Question 2

Which HTTP status code is the standard industry response when an API successfully creates a new record in the database?

14. Interview Questions

  • Q: Explain the purpose of Laravel Sanctum. How does Token-based authentication for APIs differ from Session-based authentication for web browsers?
  • Q: What is an HTTP Status Code? Give examples of when you would return a 200, a 201, a 404, and a 422 in an API endpoint.

15. FAQs

Q: Can one Laravel application serve both HTML views and a JSON API? A: Yes! This is incredibly common. Your web.php routes serve the Admin Dashboard (HTML), while your api.php routes serve the Mobile App (JSON). They both interact with the exact same database and Eloquent Models.

16. Summary

In Chapter 15, we decoupled our backend from the browser. By utilizing the api.php routing file and returning JSON responses, our Laravel application evolved into a universal data provider. We learned how to structure API responses with standard HTTP Status Codes and explored the concepts of stateless Token Authentication via Laravel Sanctum, paving the way for integrations with React, Vue, iOS, and Android clients.

17. Next Chapter Recommendation

Whether you are building Web Views or JSON APIs, hackers are trying to break your application. Proceed to Chapter 16: Laravel Security Best Practices.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·