0% complete

Advanced PHP · Lesson 9 of 10

REST APIs

Use resource-oriented URLs and HTTP methods consistently.

Lesson

REST-style APIs identify resources with URLs and use HTTP methods for operations: GET reads, POST creates, PUT or PATCH updates, and DELETE removes. Return meaningful status codes and make retries safe where possible. Document authentication, validation errors, pagination, and versioning as part of the contract. An endpoint must still authorize access to each requested resource. 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 REST 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

REST APIs
PHP
http_response_code(201);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['data' => ['id' => 42]], JSON_THROW_ON_ERROR);
Expected output
HTTP 201 with a JSON representation of the created resource

Key points

  • Use resource-oriented URLs and HTTP methods consistently.
  • 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.