Junior — Middle
How will you implement request handling for API endpoints?
sobes.tech AI
Answer from AI
Handling requests to API endpoints in PHP is usually implemented through routing, which directs requests to the appropriate controllers or handlers. You can use frameworks (such as Laravel, Symfony) or your own routing implementation.
Main steps:
- Receive the HTTP request and determine the method (GET, POST, etc.) and path.
- Match the path with a registered route.
- Call the corresponding controller or function that processes the request.
- Perform business logic, retrieve data from the database or other sources.
- Return a response in JSON format or other, with the necessary HTTP headers.
Example of simple processing without a framework:
$requestUri = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestUri === '/api/users' && $requestMethod === 'GET') {
// Get list of users
$users = getUsersFromDatabase();
header('Content-Type: application/json');
echo json_encode($users);
} else {
http_response_code(404);
echo json_encode(['error' => 'Not found']);
}
For more complex projects, it is recommended to use frameworks with support for REST, middleware, validation, and authentication.