Project: A Small JSON API
💻 PHPBuild a clean JSON endpoint that lists, creates and validates records.
This project turns the pieces of the PHP course into one small API that another application could use.
- 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);Practice
- Add a GET branch that returns a list of three students.
- Return 404 when an id does not exist.
- 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
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.
Expected Output
Valid requests return 201; missing fields return 422 with a message.
Lesson Nav
PHP Course
0/9 lessons completed
- 1 PHP Basics Tutorial
- 2 Functions and Arrays Tutorial
- 3 PHP Forms and User Input Tutorial
- 4 PHP and MySQL Database Tutorial
- 5 Build a Blog System Project
- 6 Classes, Objects and Methods Tutorial
- 7 Validation and Secure Input Tutorial
- 8 Working with JSON and APIs Tutorial
- 9 Project: A Small JSON API Project