Summary - JSON and API
Build a simple user API with json_encode, header and HTTP methods.
Summary: data format and API
In this section you learned to produce API responses in a structured data format. The encode function converts an array to a string; the UNESCAPED_UNICODE flag keeps accented letters. The decode function turns a string back into an array; assoc=true gives an associative array.
You set the Content-Type header with the header function, manage REST resources with HTTP methods, and catch errors with last_error_msg. Now let's combine all parts to produce a simple API response.
Mini API: respond by method
Now combine what you learned: a $method variable holds a simulated request method. Set the Content-Type header with header, then check the method with an if. If it is GET, encode a resource as a string and print it.
In this mini API, the header, method dispatch and data format conversion all come together. Real APIs use $_SERVER['REQUEST_METHOD'] instead of $method; the flow is the same.
Exercise Produce a simple API response
First set the Content-Type: application/... header with header. Then check the method with if ($method === 'GET') and inside the block write echo encode(['id' => 1, 'name' => 'Alex'], UNESCAPED_UNICODE);. The $method variable is already defined above.
Show example solution
First call header, then check GET with if, and inside the block call echo encode.
Example solution:
header('Content-Type: application/...');
if ($method === 'GET') {
echo encode(['id' => 1, 'name' => 'Alex'], UNESCAPED_UNICODE);
}
Test yourself
-
Which step comes first when producing an API response?
- First set Content-Type with header, then print the string with encode
- First call encode, then set the header
- First call decode, then set the header
- Just print the string with echo, no header needed
Show answer
First set Content-Type with header, then print the string with encode — Correct. header must be called before output; then encode prints the string.
-
Method dispatch
$method = 'GET'; if ($method === '____') { echo encode(['id' => 1, 'name' => 'Alex'], UNESCAPED_UNICODE); }Show answer
$method = 'GET'; if ($method === 'GET') { echo encode(['id' => 1, 'name' => 'Alex'], UNESCAPED_UNICODE); } -
Match the section concepts
- json_encode
- converts array to string
- json_decode
- converts string to array
- header
- sets Content-Type
- file_get_contents
- reads from file or URL