The Goal: Becoming a Provider, Not Just a Consumer
In the last lesson, our application acted as a "client," requesting data from an external server. In this final lesson, we will flip the roles. Our application will become the "server," providing data to any client that asks for it. This is a fundamental skill for building modern applications that can integrate with mobile apps, JavaScript frameworks, or other services.
Our specific goal is to create an API endpoint at /api.php?request=posts
that will return a JSON list of our 5 most recent blog posts.
Step 1: Key PHP Functions and Headers
To create an API, there are two crucial steps your PHP script must take:
- Set the Correct Content-Type Header: You must tell the client (the browser, app, etc.) that the data you are sending is JSON, not HTML. We do this with the
header()
function. - Encode Your Data as JSON: You must convert your PHP array of data into a JSON formatted string. We do this with the
json_encode()
function.
Additionally, we'll set an Access-Control-Allow-Origin
header. This is a security feature called CORS that tells browsers it's okay for other websites to request data from our API.
Step 2: Creating the API Entry Point
We will create a single new file in the root of your project called api.php
. This file will handle all incoming API requests.
Create a new file: api.php
<?php
// api.php - A simple API endpoint for our site.
// --- Step 1: Set HTTP Headers ---
// Tell the client that the content type is JSON
header("Content-Type: application/json; charset=UTF-8");
// Allow cross-origin requests (for public APIs)
header("Access-Control-Allow-Origin: *");
// --- Step 2: Include Configuration and Connect to DB ---
require_once 'config.php';
// --- Step 3: A Simple Router for API Requests ---
// We'll check a URL parameter to decide what data to send.
$request = $_GET['request'] ?? null;
switch ($request) {
case 'posts':
// Handle the request for posts
try {
$stmt = $pdo->prepare("SELECT title, slug, created_at FROM posts ORDER BY created_at DESC LIMIT 5");
$stmt->execute();
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Set a success status and include the data
$response = [
'status' => 'success',
'data' => $posts
];
http_response_code(200); // OK
} catch (\PDOException $e) {
// If there's a database error
$response = [
'status' => 'error',
'message' => 'Failed to fetch posts.'
];
http_response_code(500); // Internal Server Error
}
break;
default:
// If the request is invalid or not found
$response = [
'status' => 'error',
'message' => 'Invalid request. Please specify a valid endpoint (e.g., ?request=posts).'
];
http_response_code(404); // Not Found
break;
}
// --- Step 4: Encode the Response and Send It ---
// json_encode() converts our PHP array into a JSON string.
// JSON_PRETTY_PRINT makes the output human-readable.
echo json_encode($response, JSON_PRETTY_PRINT);
Your Mission: Testing Your First API
- Create the new file
api.php
in the root directory of your website. - Copy and paste the code above into the file.
- Test it! Open your web browser and navigate to the following URL:
https://startwithsite.com/api.php?request=posts
You shouldn't see a normal webpage. Instead, you should see a raw text page containing a beautifully formatted JSON object. It will have a "success" status and a "data" array containing the titles and slugs of your 5 latest blog posts. Browser extensions like "JSON Viewer" can make this even easier to read.
You have successfully created your first API!
Course Conclusion!
Congratulations! You have completed the entire learning path, from the fundamentals of modern OOP to building a complete MVC framework, using professional tools like Composer and Git, and finally, interacting with and building your own APIs.
You now possess the foundational knowledge and practical skills that form the backbone of professional PHP development. The journey of a developer is one of continuous learning, and you have built an incredible foundation to tackle any new challenge that comes your way. Well done!