Advanced PHP · Lesson 8 of 10
PHP APIs
Build an API endpoint that validates input and returns structured JSON.
Lesson
An API exposes application operations through a defined request and response contract. Validate method, content type, authentication, authorization, and request data. Return appropriate HTTP status codes and a stable JSON shape; do not expose internal exceptions, credentials, or database details.
This response sets the JSON content type before encoding a small result.
Further guidance
Make failure behavior explicit at system boundaries: validate decoded data, handle expected exceptions, and log diagnostics without exposing them to visitors. Keep dependencies locked and current, use a consistent namespace/autoloading scheme, and test error paths as well as successful responses.
Practice task: Create a fresh example for PHP APIs. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
PHP APIs
PHP
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['data' => ['status' => 'ready']], JSON_THROW_ON_ERROR);
Expected output
{"data":{"status":"ready"}}Key points
- Build an API endpoint that validates input and returns structured JSON.
- Handle expected errors explicitly without exposing diagnostics.
- Keep dependency and runtime configuration reproducible.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.