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. Openroutes/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
5. Returning JSON from a Controller
When building an API, you do not usereturn 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
*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
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 like1|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
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_adminorpassword_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.
Explain the difference between
routes/web.phpandroutes/api.phpregarding 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. Yourweb.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 theapi.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.