PHP Restful APIs
RESTful APIs (Representational State Transfer) are widely used in modern web applications to enable communication between different systems over HTTP. PHP is commonly used to build REST APIs due to its ease of integration with web technologies and support for various frameworks. This article covers common interview questions and answers related to creating and working with RESTful APIs in PHP.
What is a RESTful API?
Answer:
A RESTful API (Representational State Transfer) is an architectural style that allows communication between a client and server over HTTP. It uses standard HTTP methods like GET, POST, PUT, DELETE, and PATCH to perform CRUD (Create, Read, Update, Delete) operations. RESTful APIs typically exchange data in formats like JSON or XML and are stateless, meaning each request contains all the information necessary for the server to fulfill it.
What are the main HTTP methods used in RESTful APIs?
Answer:
The main HTTP methods used in RESTful APIs are:
- GET: Retrieve data from the server.
- POST: Create new data on the server.
- PUT: Update or replace existing data.
- PATCH: Partially update existing data.
- DELETE: Delete data from the server.
How do you create a simple RESTful API in PHP?
Answer:
To create a simple RESTful API in PHP, you handle different HTTP requests by checking the request method and providing the appropriate response. You can use $_SERVER['REQUEST_METHOD'] to determine the request method.
Example:
header("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
// Retrieve data
echo json_encode(["message" => "GET request received"]);
break;
case 'POST':
// Create data
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode(["message" => "POST request received", "data" => $data]);
break;
case 'PUT':
// Update data
echo json_encode(["message" => "PUT request received"]);
break;
case 'DELETE':
// Delete data
echo json_encode(["message" => "DELETE request received"]);
break;
default:
http_response_code(405);
echo json_encode(["message" => "Method not allowed"]);
break;
}
How do you handle JSON data in a RESTful API with PHP?
Answer:
PHP provides functions like json_encode() to send data in JSON format and json_decode() to parse incoming JSON data.
- Sending JSON data: Use json_encode() to convert PHP data structures (arrays or objects) into JSON format.
$data = ['name' => 'John Doe', 'age' => 30];
echo json_encode($data);- Receiving JSON data: To handle incoming JSON data, use file_get_contents("php://input") to read the raw request body and json_decode() to convert it into a PHP array or object.
$input = file_get_contents("php://input");
$data = json_decode($input, true); // Convert JSON to array
print_r($data);What are the main components of a RESTful API in PHP?
Answer:
The main components of a RESTful API in PHP are:
- Routes: Define the URL paths and map them to specific actions (e.g., /users, /products/1).
- HTTP Methods: Handle GET, POST, PUT, DELETE, etc., for different CRUD operations.
- Request Data: Data sent by the client in the URL, query parameters, headers, or body.
- Response Data: The API responds with data (usually in JSON format) and appropriate HTTP status codes.
- Status Codes: Provide feedback to the client about the outcome of the request (e.g., 200 OK, 404 Not Found, 500 Internal Server Error).
How do you handle routing in a RESTful API in PHP?
Answer:
You can implement routing in a RESTful API by examining the requested URL and HTTP method. Based on the URL path and method, you can route the request to the appropriate handler.
Example:
$requestUri = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestUri == '/api/users' && $requestMethod == 'GET') {
// Handle GET request for users
echo json_encode(["message" => "List of users"]);
} elseif ($requestUri == '/api/users' && $requestMethod == 'POST') {
// Handle POST request to create a user
echo json_encode(["message" => "User created"]);
} else {
http_response_code(404);
echo json_encode(["message" => "Route not found"]);
}What are common HTTP status codes used in RESTful APIs?
Answer:
Common HTTP status codes used in RESTful APIs include:
- 200 OK: The request was successful.
- 201 Created: The resource was successfully created (used with POST).
- 204 No Content: The request was successful, but there is no content to return (used with DELETE or PUT).
- 400 Bad Request: The request was malformed or invalid.
- 401 Unauthorized: Authentication is required or failed.
- 403 Forbidden: The client does not have permission to access the resource.
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: The server encountered an unexpected condition.
How do you send HTTP response headers in a RESTful API in PHP?
Answer:
You can send HTTP response headers in PHP using the header() function. This allows you to set content types, status codes, and other headers.
Example:
header("Content-Type: application/json");
header("HTTP/1.1 200 OK");Example for sending a 404 Not Found status:
http_response_code(404); // Sets HTTP status to 404
echo json_encode(["message" => "Resource not found"]);How do you implement authentication in a RESTful API in PHP?
Answer:
RESTful APIs commonly implement authentication using:
- API keys: The client sends a unique API key in the request header, and the server verifies the key to authenticate the client.
- Bearer tokens: The client sends a token (e.g., JWT) in the Authorization header. The server verifies the token to authenticate the client.
- Basic Authentication: The client sends the username and password in the Authorization header encoded in base64.
Example of checking an API key:
$headers = apache_request_headers();
$apiKey = $headers['X-API-Key'] ?? '';
if ($apiKey !== 'your_secret_key') {
http_response_code(401);
echo json_encode(["message" => "Unauthorized"]);
exit;
}
echo json_encode(["message" => "Authorized"]);How do you handle CORS in a RESTful API in PHP?
Answer:
CORS (Cross-Origin Resource Sharing) controls how web pages can request resources from a different domain. To handle CORS in a RESTful API, you need to send specific headers that allow cross-origin requests.
Example:
header("Access-Control-Allow-Origin: *"); // Allow all domains
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");You may also need to handle OPTIONS requests, which are sent by browsers to check if the actual request is allowed.
Example for handling OPTIONS requests:
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 OK");
exit;
}What is JSON Web Token (JWT), and how is it used in PHP for RESTful APIs?
Answer:
JSON Web Token (JWT) is a compact, URL-safe token used to represent claims between two parties (usually for authentication). JWT is commonly used in RESTful APIs for stateless authentication, where the token is sent in the Authorization header of each request.
Example of verifying a JWT in PHP:
$headers = apache_request_headers();
$jwt = $headers['Authorization'] ?? '';
if ($jwt) {
try {
$decoded = JWT::decode($jwt, 'your_secret_key', ['HS256']);
echo json_encode(["message" => "Token valid", "user" => $decoded]);
} catch (Exception $e) {
http_response_code(401);
echo json_encode(["message" => "Invalid token"]);
}
} else {
http_response_code(401);
echo json_encode(["message" => "Authorization header missing"]);
}How do you version a RESTful API in PHP?
Answer:
You can version a RESTful API by including the version number in the URL or the request headers. The URL versioning method is more common and straightforward.
Example of versioning in the URL:
/api/v1/users // Version 1 of the API
/api/v2/users // Version 2 of the APIExample in PHP:
$requestUri = $_SERVER['REQUEST_URI'];
if (strpos($requestUri, '/api/v1') !== false) {
// Handle version 1
echo json_encode(["message" => "Version 1 API"]);
} elseif (strpos($requestUri, '/api/v2') !== false) {
// Handle version 2
echo json_encode(["message" => "Version 2 API"]);
}You can also use custom headers for versioning:
X-API-Version: 1How do you paginate results in a RESTful API in PHP?
Answer:
Pagination in a RESTful API is implemented by returning a limited number of results per request and providing links or metadata for navigating through pages of results.
Example of basic pagination:
$page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 10;
$offset = ($page - 1) * $limit;
// Query to retrieve paginated results
$query = "SELECT * FROM users LIMIT $limit OFFSET $offset";You can include pagination metadata in the response:
$totalItems = 100; // Total number of records
$totalPages = ceil($totalItems / $limit);
echo json_encode([
"data" => $users, // Paginated data
"pagination" => [
"currentPage" => $page,
"totalPages" => $totalPages,
"itemsPerPage" => $limit
]
]);How do you handle errors in a RESTful API in PHP?
Answer:
In a RESTful API, errors should be handled gracefully by returning proper HTTP status codes and descriptive error messages in JSON format. Common status codes for errors include 400 Bad Request, 401 Unauthorized, 404 Not Found, and 500 Internal Server Error.
Example of handling errors:
if (!$data) {
http_response_code(400); // Bad Request
echo json_encode(["message" => "Invalid input"]);
exit;
}
// For an internal server error
try {
// Database query or operation
} catch (Exception $e) {
http_response_code(500); // Internal Server Error
echo json_encode(["message" => "Server error", "error" => $e->getMessage()]);
}What is the difference between REST and SOAP APIs?
Answer:
- REST (Representational State Transfer):
- Protocol: Uses standard HTTP methods (GET, POST, PUT, DELETE).
- Data format: Typically uses JSON or XML.
- Stateless: Each request is independent, containing all necessary information.
- Scalability: More scalable and easier to use with web technologies.
- SOAP (Simple Object Access Protocol):
- Protocol: A protocol that uses XML for messaging.
- Data format: Only uses XML for request and response payloads.
- Stateful or Stateless: Can be either stateful or stateless.
- Complexity: More complex, with strict standards and protocol definitions.