What you need

  • Computer and internet: a laptop or desktop and a stable connection
  • System: Windows 10 or 11, macOS or Linux
  • Tools: PHP 8.3 or newer, Composer, Git and a code editor (the Laravel installation guide lists the official one-command installer)
  • Before this: Your first Laravel route

Download only from each tool's official site and check the address before installing.

What you will learn

You will build a small API in Laravel that lists, shows and creates lessons. It returns JSON, checks every input with validation, and answers with the correct status codes. You will test it from the terminal like a professional.

Before this lesson, finish Your first Laravel route. You keep building the same project, ~/ewoi-learning/laravel-app, and every command below runs inside that folder.

Ewoi

A website talks to people. An API talks to other programs: a mobile app, a payment provider, another website. Same ideas, different audience.

What an API is, in plain words

When you open a website, the server sends HTML: a page designed for human eyes. An API sends data instead, usually as JSON, designed for another program to read and use.

A restaurant menu is a good picture. It lists exactly what you can order and how to ask for it. You do not need to know how the kitchen works. An API is a menu for programs: it lists what they can ask for, and what they will get back.

When a banking app shows your balance, it calls the bank's API in the background. When a shop takes M-Pesa payments, it talks to a payment API.

REST in one table

REST is a common style for designing APIs. Its main idea: addresses name things, and the HTTP method says what to do with them. Each method-plus-address combination is called an endpoint.

Method Address Meaning Success code
GET /api/lessons List lessons 200 OK
GET /api/lessons/5 Show lesson 5 200 OK
POST /api/lessons Create a new lesson 201 Created
PUT or PATCH /api/lessons/5 Change lesson 5 200 OK
DELETE /api/lessons/5 Remove lesson 5 204 No Content

Notice the address /api/lessons appears twice. GET means "list them", POST means "add one". The method changes the meaning.

What JSON looks like

{
  "id": 5,
  "title": "Build a REST API",
  "level": "intermediate",
  "published": true,
  "tags": ["laravel", "api"]
}

Curly braces hold an object: names in double quotes, a colon, then a value. Values can be text (in double quotes), numbers, true or false, lists in square brackets, or other objects.

Step 1: Prepare the project for an API

In your project folder:

cd ~/ewoi-learning/laravel-app
php artisan install:api

This creates routes/api.php, the file for API routes, and installs Laravel's API sign-in package (Sanctum), which you will use in a later lesson. Answer yes if it asks to run the database migrations. Every route in routes/api.php automatically starts with /api.

The output ends with API scaffolding installed. Please add the [Laravel\Sanctum\HasApiTokens] trait to your User model. You can ignore that request for now: it is for signing in with tokens, a later lesson. Open routes/api.php and you will see it already starts like this:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Those use lines tell PHP which classes the file uses. Remember them: you will add one more in Step 3.

Step 2: Create the lessons table and model

php artisan make:model Lesson -m

This makes two files: a model, app/Models/Lesson.php (the PHP class that represents one lesson), and a migration (a file describing a database table). Open the new file in database/migrations whose name ends in create_lessons_table.php and change the table definition to:

Schema::create('lessons', function (Blueprint $table) {
    $table->id();
    $table->string('title', 200);
    $table->string('level', 20);
    $table->timestamps();
});

timestamps() adds created_at and updated_at columns that Laravel fills in for you. Create the table:

php artisan migrate

The output lists your new migration followed by DONE. If it says Nothing to migrate, the file was not saved: save it and run the command again.

Now open app/Models/Lesson.php. Keep the namespace and use lines at the top, and replace the // inside the class with the list of columns that may be filled from a request:

class Lesson extends Model
{
    protected $fillable = ['title', 'level'];
}

You may notice that Laravel 13's own app/Models/User.php writes the same kind of list as #[Fillable(['name', 'email', 'password'])] just above the class. That is a newer way to say the same thing; both work.

Why $fillable?It is a safety list. Without it, a request could try to set any column, such as a hidden is_admin field on a user. Laravel only fills the columns you allow here.

Step 3: The list endpoint

Open routes/api.php. At the top, under the two existing use lines, add one line:

use App\Models\Lesson;

Only add Lesson: Request is already imported, and importing the same name twice stops the whole file with Cannot use Illuminate\Http\Request as Request because the name is already in use. Then, at the bottom of the file, add the list endpoint:

Route::get('/lessons', function () {
    return Lesson::query()->latest()->paginate(20);
});

latest() orders newest first. paginate(20) returns at most 20 lessons per page, plus information about the other pages. Never return "all rows": the day you have 100,000 lessons, that endpoint would bring your server to its knees.

When a route returns a model or a list of models, Laravel turns it into JSON automatically.

Step 4: Test it with curl

curl is a terminal tool that sends HTTP requests, already installed on macOS, Linux and Windows 10 or newer. Make sure php artisan serve is running in another terminal, then:

curl -s -H "Accept: application/json" http://127.0.0.1:8000/api/lessons
Part Meaning
-s Silent: hide the progress bar
-H "Accept: application/json" Add a header saying "I want JSON back"
The address Which endpoint to call

You will see JSON with an empty data list. The database is empty, so let us add lessons.

Step 5: The create endpoint, with validation

Add to routes/api.php:

Route::post('/lessons', function (Request $request) {
    $data = $request->validate([
        'title' => ['required', 'string', 'max:200'],
        'level' => ['required', 'in:beginner,intermediate,advanced'],
    ]);

    $lesson = Lesson::create($data);

    return response()->json($lesson, 201);
});

Read the validation rules like a checklist the data must pass:

Rule Meaning
required Must be present and not empty
string Must be text
max:200 At most 200 characters
in:beginner,intermediate,advanced Must be exactly one of these values

If any rule fails, Laravel stops right there and replies with 422 Unprocessable Content and a JSON list of what was wrong. Your code below never runs with bad data. If everything passes, $data contains only the checked fields, and you create the lesson and reply 201 Created.

Ewoi

Never trust input, even from your own app. Some mistakes are honest typos and some are deliberate attacks. Validation stops both at the door.

Step 6: Test good and bad requests

Create a lesson:

curl -s -X POST http://127.0.0.1:8000/api/lessons -H "Accept: application/json" -H "Content-Type: application/json" -d "{\"title\": \"Git basics\", \"level\": \"beginner\"}"

-X POST sets the method, Content-Type: application/json says you are sending JSON, and -d is the data. (The \" are double quotes that the terminal passes through inside the data.) You get the new lesson back, with its id.

Now send bad data on purpose:

curl -s -i -X POST http://127.0.0.1:8000/api/lessons -H "Accept: application/json" -H "Content-Type: application/json" -d "{\"title\": \"\", \"level\": \"expert\"}"

The -i option shows the status line. You get 422 and messages for both fields. Your API just protected itself.

Ask your AI assistant

I am testing a Laravel 13 API with curl. Here is my command: [paste it] and here is the response: [paste it]. Explain the status code and the response in simple words, and tell me what to change if it is not what I expected.

Step 7: Show one lesson, or a proper 404

Route::get('/lessons/{lesson}', function (Lesson $lesson) {
    return $lesson;
});

Because the parameter is typed as Lesson, Laravel looks the lesson up by its id for you. This is called route model binding. If no lesson has that id, Laravel replies 404 Not Found automatically. Test both:

curl -s -H "Accept: application/json" http://127.0.0.1:8000/api/lessons/1
curl -s -i -H "Accept: application/json" http://127.0.0.1:8000/api/lessons/9999

Status codes your API should use

Situation Code
Read worked 200 OK
Something was created 201 Created
Deleted, nothing to return 204 No Content
Input failed validation 422 Unprocessable Content
Not signed in 401 Unauthorized
Signed in but not allowed 403 Forbidden
Does not exist 404 Not Found
Too many requests 429 Too Many Requests
Your code crashed 500 Server Error

Correct codes matter because the program calling your API decides what to do next from the code, before it even reads the body.

Step 8: Save your work

Your routes/api.php should now look like this (the /user route came from install:api; leave it):

<?php

use App\Models\Lesson;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');

Route::get('/lessons', function () {
    return Lesson::query()->latest()->paginate(20);
});

Route::post('/lessons', function (Request $request) {
    $data = $request->validate([
        'title' => ['required', 'string', 'max:200'],
        'level' => ['required', 'in:beginner,intermediate,advanced'],
    ]);

    $lesson = Lesson::create($data);

    return response()->json($lesson, 201);
});

Route::get('/lessons/{lesson}', function (Lesson $lesson) {
    return $lesson;
});

The files this lesson added or changed:

laravel-app/
├── app/Models/Lesson.php
├── database/migrations/xxxx_xx_xx_xxxxxx_create_lessons_table.php   (your date and time)
├── routes/api.php
└── (from install:api) bootstrap/app.php, composer.json, composer.lock, config/sanctum.php and a tokens migration

Commit it all:

git add .
git commit -m "Add a lessons API with validation"

git status should then say nothing to commit, working tree clean. To compare with ours, or to run a test that checks every endpoint, open https://github.com/ewoibuilds/practical-software-development/tree/main/step-03-build-a-rest-api, copy tests/Feature/LessonApiTest.php into your tests/Feature/ folder and run php artisan test. All tests should pass.

Before this goes live

This API is a learning version. A real one also needs:

  • Authentication: who is calling? Only signed-in or approved programs should create lessons.
  • Authorisation: is this caller allowed to do this?
  • Rate limiting: a limit on requests per minute, so nobody can flood it.
  • Controllers and API resources: to keep the code organised and control exactly which fields are returned.

Each of these is its own lesson. Use the request box below this lesson to tell us which you want first.

Common beginner mistakes

Problem Cause Fix
You get an HTML page instead of JSON The address does not start with /api, so it reached a web route or the web 404 page (Laravel 13 answers errors on /api addresses as JSON) Check the address, and keep sending -H "Accept: application/json"
404 on /lessons API routes start with /api Use /api/lessons
Add [title] to fillable property The model has no $fillable list Add protected $fillable = ['title', 'level'];
405 Method Not Allowed Right address, wrong method Check the method with php artisan route:list
no such table: lessons The migration was not run Run php artisan migrate

Recap

  • An API returns data, usually JSON, for other programs.
  • In REST, the address names the thing and the method says what to do.
  • Validate every input; Laravel replies 422 with clear errors when it fails.
  • Return the right status codes: 200, 201, 204, 404, 422.
  • Paginate lists; never return every row.

Your practice task

  1. Add PATCH /api/lessons/{lesson} that validates and updates the title or level, returning 200.
  2. Add DELETE /api/lessons/{lesson} that deletes it and returns 204 (return response()->noContent();).
  3. Test each endpoint with curl, including one bad request each, and write the status codes you got in your notes. Commit when both work.

Ask your AI assistant

I am learning Laravel 13 and wrote a PATCH route for my lessons API: [paste the route]. Do not write the code for me. Tell me whether it validates input, returns the right status code and returns 404 for a missing lesson, and give me one hint for each thing that is missing.

Check your understanding

1. In REST, what is the difference between GET /api/lessons and POST /api/lessons?

The address names the thing (lessons). The method says what to do with it.

2. A request sends level "expert", but the rule is in:beginner,intermediate,advanced. What does Laravel reply?

Validation fails before your code runs, and Laravel replies 422 Unprocessable Content with the errors.

3. Which status code means "created successfully"?

201 Created tells the caller a new thing exists. 204 means success with nothing to return, often after a delete.

4. Why use paginate(20) instead of returning every lesson?

Always limit list endpoints. Callers can ask for the next page when they need more.

Get the code on GitHub

Found this useful?

Every lesson stays free. Tap the thumbs up so we know what works, or say thanks with a soda or a coffee: it pays for hosting and new lessons.

Buy me a sodaBuy me a coffee

Want more on this?

Tell us which part was not clear, ask for a follow-up lesson, or request a lesson on any topic. We read every request.

I would like
Only to tell you when it is ready.

WhatsApp

Join the channelChat with us

Free lessons and updates in the channel. Questions about learning or training? Chat with us.