APIs (Application Programming Interfaces) have become a core component of web development, enabling communication between different software applications. While PHP is known for building dynamic websites, it’s also highly effective for creating APIs. In this blog post, we’ll walk through the process of creating a simple API in PHP using native PHP functions without relying on frameworks.
By the end of this guide, you’ll learn how to:
- Set up a PHP environment.
- Create a simple API endpoint.
- Process HTTP requests and return JSON responses.
- Test your API with Postman.
Prerequisites
- Basic knowledge of PHP.
- A local server environment like XAMPP, WAMP, or Laravel’s built-in server.
- Postman or any tool for API testing.
Step 1: Setting Up a PHP Environment
Before creating the API, ensure that you have a PHP environment set up. You can use XAMPP, WAMP, or even the built-in PHP server.
Using PHP’s Built-in Server
If you have PHP installed, navigate to the folder where you want to create your API and run:
php -S localhost:8000
This command will start a PHP server at http://localhost:8000
.
Step 2: Creating the API Folder Structure
Create a new folder for your project. Inside this folder, create the following structure:
my-php-api/
├── index.php
├── data/
│ └── users.json
index.php
: This file will handle API requests.data/users.json
: This file will simulate a database for user data.
Sample users.json
File
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane Doe",
"email": "jane@example.com"
}
]
This JSON file contains sample user data that our API will serve.
Step 3: Create the index.php
File
Now, let’s write the logic for our API inside index.php
. We’ll create a simple GET request that returns the list of users.
Sample Code for index.php
<?php
// Set headers to allow CORS and return JSON data
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// Simulating a "database" with a JSON file
$users = file_get_contents('data/users.json');
$users = json_decode($users, true);
// Get the request method
$requestMethod = $_SERVER['REQUEST_METHOD'];
// Handle GET request
if ($requestMethod == 'GET') {
// Check if an ID was passed as a query parameter
if (isset($_GET['id'])) {
$userId = (int)$_GET['id'];
$user = array_filter($users, fn($user) => $user['id'] === $userId);
if (!empty($user)) {
echo json_encode(array_values($user)[0]);
} else {
http_response_code(404);
echo json_encode(["message" => "User not found"]);
}
} else {
// Return all users if no ID is provided
echo json_encode($users);
}
} else {
http_response_code(405);
echo json_encode(["message" => "Method not allowed"]);
}
?>
Explanation
- Headers: We set headers to allow cross-origin requests (
Access-Control-Allow-Origin: *
) and specify that the content is JSON. - Read Users: We read the user data from
users.json
and decode it into an array. - Request Method: We check the request method (
GET
in this case) and handle it accordingly. - Filter by ID: If an
id
is provided in the query string (e.g.,?id=1
), we filter and return the specific user. If noid
is provided, we return all users. - Error Handling: If a user with the specified ID is not found, we return a
404
response. If a different request method is used (e.g.,POST
orDELETE
), we return a405
error.
Step 4: Testing the API
Now that our API is ready, we need to test it using Postman or a browser.
Testing with Postman
- Open Postman and create a new GET request.
- Set the URL to
http://localhost:8000/index.php
. - Click Send.
You should see the list of users as a JSON response:
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane Doe",
"email": "jane@example.com"
}
]
Testing with an ID Parameter
To get a specific user by ID, append ?id=1
to the URL:
http://localhost:8000/index.php?id=1
This should return:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
If you provide an invalid ID like ?id=99
, you will get a 404
error:
{
"message": "User not found"
}
Step 5: Adding More Request Methods
To make the API more versatile, you might want to handle other HTTP methods like POST, PUT, and DELETE.
Adding a POST Request
To add new users, update index.php
to include:
if ($requestMethod == 'POST') {
$data = json_decode(file_get_contents("php://input"), true);
$newUser = [
"id" => count($users) + 1,
"name" => $data['name'],
"email" => $data['email']
];
$users[] = $newUser;
file_put_contents('data/users.json', json_encode($users));
echo json_encode($newUser);
}
This code handles a POST request to add a new user, saves it to users.json
, and returns the newly added user.
Testing POST with Postman
- Set the request method to POST.
- Use the URL
http://localhost:8000/index.php
. - Under the Body tab, select raw and choose JSON as the format.
- Provide the user data in JSON format:
{
"name": "Alice Smith",
"email": "alice@example.com"
}
Click Send, and you should see the new user added:
{
"id": 3,
"name": "Alice Smith",
"email": "alice@example.com"
}
Step 6: Conclusion
Congratulations! You’ve successfully built a simple API using native PHP. This guide covered setting up a basic PHP environment, creating a simple API with GET and POST methods, and testing it using Postman. Although this API is basic, it serves as a foundation for building more complex APIs in PHP.
Key Takeaways:
- Use PHP’s Built-in Server for quick testing.
- JSON files can simulate databases for small projects.
- Postman is a valuable tool for testing APIs.
For production-ready APIs, you might consider using a PHP framework like Laravel or Symfony, which provide more powerful tools for routing, authentication, and data handling.
Further Reading
I hope you found this guide helpful! Happy coding!
Feel free to use this content