New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› PHP› Project: A Small JSON API

Project: A Small JSON API

💻 PHP

Build a clean JSON endpoint that lists, creates and validates records.

Lesson 9 of 9 Project
0 of 9 completed

This project turns the pieces of the PHP course into one small API that another application could use.

By the end of this lesson you can:
  • Structure a JSON endpoint.
  • Read and validate a request body.
  • Return correct status codes.

Set Headers

Tell the client what you are returning. Set the content type before printing any output.

<?php

header('Content-Type: application/json; charset=utf-8');

Read the Request

Read the raw body for JSON requests, decode it and validate the fields. Return 422 for invalid data instead of a 200 with an error message.

<?php

$body = file_get_contents('php://input');
$input = json_decode($body, true) ?? [];

if (empty($input['name'])) {
    http_response_code(422);
    echo json_encode(['error' => 'name is required']);
    exit;
}

Return a Response

A successful create returns 201 and the created record. A list returns 200 and an array. Errors use 400, 404, 422 or 500 with a short JSON message.

<?php

http_response_code(201);
echo json_encode([
    'id' => 7,
    'name' => $input['name'],
], JSON_UNESCAPED_UNICODE);
Tip Keep responses predictable. The same shape for every error makes client code much simpler.

Practice

  1. Add a GET branch that returns a list of three students.
  2. Return 404 when an id does not exist.
  3. Reject a name longer than 60 characters with a 422 response.

Hands-on exercise

Build a POST endpoint that:
1. Sets a JSON content type.
2. Reads a JSON body containing name and email.
3. Returns 422 with an error when either field is missing.
4. Returns 201 and the record when both are valid.

Recap

A small API needs clear headers, validated input, predictable errors and correct status codes.

Example

<?php

header('Content-Type: application/json; charset=utf-8');

Exercises

Exercise 1. Create endpoint Hard
Build a POST endpoint that:
1. Sets a JSON content type.
2. Reads a JSON body containing name and email.
3. Returns 422 with an error when either field is missing.
4. Returns 201 and the record when both are valid.
PHP exercise-1.php
Expected Output
Valid requests return 201; missing fields return 422 with a message.

Lesson Nav

Lesson sections