PHP - Building RESTful APIs with PHP and API Versioning

RESTful APIs have become the standard way for applications to communicate over the web. Whether it is a mobile application retrieving user information, a website displaying product details, or a third-party service integrating with a platform, APIs enable seamless data exchange between systems. PHP is widely used for developing RESTful APIs because of its simplicity, flexibility, and extensive ecosystem of frameworks and libraries.

Understanding RESTful APIs

REST stands for Representational State Transfer. It is an architectural style that uses standard HTTP methods to perform operations on resources. In a RESTful API, resources are represented through URLs, and clients interact with these resources using HTTP requests.

The primary HTTP methods used in REST APIs include:

  • GET: Retrieves data from the server.

  • POST: Creates a new resource.

  • PUT: Updates an existing resource.

  • PATCH: Partially updates a resource.

  • DELETE: Removes a resource.

For example, in an e-commerce application:

  • GET /products retrieves all products.

  • GET /products/10 retrieves a specific product.

  • POST /products creates a new product.

  • PUT /products/10 updates product information.

  • DELETE /products/10 removes a product.

These standardized operations make APIs predictable and easier to use.

Designing RESTful API Endpoints

A well-designed API uses resource-oriented URLs instead of action-oriented URLs.

Poor design:

/getProducts
/createProduct
/deleteProduct

Better RESTful design:

/products
/products/{id}

Resources should be represented using nouns rather than verbs because HTTP methods already indicate the action being performed.

Endpoints should follow consistent naming conventions, typically using plural nouns:

/users
/orders
/categories

Consistency improves readability and simplifies maintenance.

Building a RESTful API in PHP

PHP can create APIs using native code or frameworks such as Laravel, Symfony, and Slim.

A simple API structure includes:

  1. Request handling

  2. Routing

  3. Database interaction

  4. Response generation

  5. Error handling

Example endpoint:

<?php

header("Content-Type: application/json");

$products = [
    ["id" => 1, "name" => "Laptop"],
    ["id" => 2, "name" => "Smartphone"]
];

echo json_encode($products);

?>

When a client accesses the endpoint, the API returns data in JSON format, which is the most commonly used format in modern web applications.

Response:

[
  {
    "id": 1,
    "name": "Laptop"
  },
  {
    "id": 2,
    "name": "Smartphone"
  }
]

Working with HTTP Status Codes

RESTful APIs use HTTP status codes to indicate the outcome of requests.

Common status codes include:

  • 200 OK – Request completed successfully.

  • 201 Created – Resource created successfully.

  • 400 Bad Request – Invalid request data.

  • 401 Unauthorized – Authentication required.

  • 403 Forbidden – Access denied.

  • 404 Not Found – Resource does not exist.

  • 500 Internal Server Error – Server-side issue.

Example:

http_response_code(404);

echo json_encode([
    "error" => "Product not found"
]);

Status codes provide meaningful feedback to API consumers and help them handle responses appropriately.

Handling JSON Requests

Most REST APIs receive data in JSON format.

Example JSON request:

{
  "name": "Laptop",
  "price": 50000
}

Reading JSON input in PHP:

$data = json_decode(file_get_contents("php://input"), true);

$name = $data['name'];
$price = $data['price'];

This approach allows APIs to process structured data from web and mobile applications.

Authentication and Security

APIs often expose sensitive data, making security essential.

Common authentication methods include:

API Keys

Clients provide a unique key with each request.

Authorization: ApiKey abc123xyz

JWT Authentication

JSON Web Tokens allow stateless authentication.

Process:

  1. User logs in.

  2. Server generates a token.

  3. Client stores the token.

  4. Client sends the token with future requests.

  5. Server validates the token before processing.

JWT is widely used because it reduces server-side session management.

HTTPS

All API communication should occur over HTTPS to protect data from interception during transmission.

Importance of API Versioning

As applications evolve, APIs often need changes such as:

  • New features

  • Improved data structures

  • Security enhancements

  • Removal of outdated functionality

Without versioning, updates may break existing applications that depend on older API behavior.

API versioning allows developers to introduce changes while maintaining backward compatibility.

For example:

Version 1 response:

{
  "name": "John"
}

Version 2 response:

{
  "first_name": "John",
  "last_name": "Doe"
}

Without versioning, applications expecting the old structure may fail.

Common API Versioning Strategies

URL Versioning

The version number is included in the URL.

/api/v1/products
/api/v2/products

Advantages:

  • Easy to understand.

  • Simple implementation.

  • Widely adopted.

Disadvantages:

  • Multiple URLs for the same resource.

Header Versioning

Version information is sent through request headers.

Example:

Accept: application/vnd.company.v2+json

Advantages:

  • Cleaner URLs.

  • Better separation of resource and version.

Disadvantages:

  • More difficult for beginners.

  • Harder to test manually.

Query Parameter Versioning

Version is specified in query parameters.

/products?version=1
/products?version=2

Advantages:

  • Easy implementation.

Disadvantages:

  • Less commonly used.

  • May create confusion.

Among these approaches, URL versioning remains the most popular due to its simplicity.

Implementing API Versioning in PHP

Directory structure:

api/
 ├── v1/
 │    └── products.php
 └── v2/
      └── products.php

Routing example:

$version = $_GET['version'] ?? 'v1';

if ($version == 'v1') {
    include 'api/v1/products.php';
} else {
    include 'api/v2/products.php';
}

Each version can maintain its own logic while sharing common services and database layers.

Best Practices for RESTful APIs

  1. Use meaningful resource names.

  2. Return JSON responses consistently.

  3. Implement proper HTTP status codes.

  4. Validate all incoming data.

  5. Secure endpoints using authentication and HTTPS.

  6. Document APIs thoroughly.

  7. Maintain backward compatibility through versioning.

  8. Use pagination for large datasets.

  9. Handle errors consistently.

  10. Monitor API performance and usage.

Conclusion

RESTful APIs are a fundamental component of modern software development, enabling communication between applications in a standardized and scalable manner. PHP provides powerful tools and frameworks for building APIs that are secure, maintainable, and efficient. As APIs grow and evolve, versioning becomes essential to ensure that new features and improvements do not disrupt existing consumers. By combining REST principles with a well-planned versioning strategy, developers can create robust APIs that support long-term application growth and integration.