๐ PHP API Development: Building Bridges Between Apps
Imagine This: Youโre at a restaurant. You donโt walk into the kitchen to cook your own food. Instead, you tell the waiter what you want, and they bring it to you. APIs work exactly like that waiter โ they take your request to the โkitchenโ (server) and bring back what you need!
๐ What Weโre Learning Today
Think of this guide as your treasure map to understanding how apps talk to each other. By the end, youโll know:
- โ What REST APIs are (and why everyone loves them)
- โ How to send and receive data using JSON
- โ Ways to prove โitโs really youโ (authentication)
- โ The different ways to ask for things (HTTP methods)
๐ Part 1: REST API Basics
What is an API?
API stands for Application Programming Interface. Big words, simple idea!
Think of it like a menu at a restaurant:
- The menu shows what you can order
- You pick something
- The kitchen makes it
- The waiter brings it to you
An API is the menu + waiter combined! It shows what you can ask for and delivers it.
What Makes REST Special?
REST = REpresentational State Transfer
Donโt memorize that! Just remember: REST is a set of rules for how to build APIs that are:
- ๐ฏ Simple โ Easy to understand
- ๐ Consistent โ Same patterns everywhere
- ๐ Universal โ Works the same way for everyone
The Restaurant Analogy ๐ฝ๏ธ
| Restaurant | REST API |
|---|---|
| Menu | API Documentation |
| Waiter | HTTP Request |
| Kitchen | Server |
| Food | Response Data |
| Table Number | Endpoint URL |
Your First API Endpoint
An endpoint is like an address where you can ask for specific things:
// This is an endpoint for getting users
// URL: /api/users
<?php
header("Content-Type: application/json");
$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"]
];
echo json_encode($users);
?>
When someone visits /api/users, they get the list of users!
Key REST Principles
- Stateless โ Each request is independent (like ordering fresh each time)
- Client-Server โ Separation of concerns (kitchen doesnโt care who ordered)
- Uniform Interface โ Consistent URLs and methods
๐ฆ Part 2: JSON API Responses
What is JSON?
JSON = JavaScript Object Notation
Think of JSON as a universal language that all apps understand. Itโs like how emojis work everywhere! ๐
JSON Structure Made Simple
{
"name": "Pizza",
"price": 12.99,
"toppings": ["cheese", "tomato"],
"available": true
}
See those patterns?
- Curly braces
{}= a container (like a box) - Square brackets
[]= a list (like a shopping list) - Key: Value = label and its content
Sending JSON Responses in PHP
<?php
// STEP 1: Tell the browser
// "Hey, I'm sending JSON!"
header("Content-Type: application/json");
// STEP 2: Create your data
$response = [
"success" => true,
"message" => "User created!",
"user" => [
"id" => 42,
"name" => "Charlie"
]
];
// STEP 3: Convert and send
echo json_encode($response);
?>
Good vs Bad API Responses
โ Good Response (Clear & Helpful)
{
"success": true,
"data": {
"id": 1,
"name": "Alice"
},
"message": "User found!"
}
โ Bad Response (Confusing)
{"u":{"i":1,"n":"Alice"},"s":1}
Always be clear! Your future self will thank you.
Handling Errors Gracefully
<?php
header("Content-Type: application/json");
$userId = $_GET['id'] ?? null;
if (!$userId) {
http_response_code(400);
echo json_encode([
"success" => false,
"error" => "User ID is required"
]);
exit;
}
// Continue with finding user...
?>
๐ Part 3: API Authentication Methods
Why Authentication?
Imagine if anyone could walk into your house! ๐ Authentication is like a lock on your door โ it proves youโre allowed in.
The Three Main Methods
graph TD A["๐ Authentication"] --> B["API Keys"] A --> C["JWT Tokens"] A --> D["OAuth"] B --> E["Simple but less secure"] C --> F["Modern & popular"] D --> G["Login with Google/Facebook"]
Method 1: API Keys ๐
The simplest way! Like a password for your app.
<?php
header("Content-Type: application/json");
// The secret key
$validKey = "my-secret-api-key-123";
// Check if key is provided
$providedKey = $_SERVER['HTTP_X_API_KEY']
?? null;
if ($providedKey !== $validKey) {
http_response_code(401);
echo json_encode([
"error" => "Invalid API key"
]);
exit;
}
// Key is valid! Continue...
echo json_encode(["message" => "Welcome!"]);
?>
How to use: Send the key in a header:
X-API-KEY: my-secret-api-key-123
Method 2: JWT (JSON Web Tokens) ๐ซ
Like a concert wristband โ it proves you paid and can enter!
<?php
// Creating a simple JWT concept
// The payload (what's inside)
$payload = [
"user_id" => 42,
"name" => "Alice",
"exp" => time() + 3600 // expires in 1 hour
];
// In real apps, use a JWT library
// This is simplified for learning
$header = base64_encode('{"alg":"HS256"}');
$data = base64_encode(json_encode($payload));
$secret = "my-secret-key";
$signature = hash_hmac('sha256',
"$header.$data", $secret);
$token = "$header.$data.$signature";
echo $token;
?>
Method 3: OAuth 2.0 ๐
Like using your ID to get into a club โ you prove who you are once, and youโre in!
This is what happens when you click โLogin with Googleโ:
graph TD A["Your App"] --> B["Redirect to Google"] B --> C["User logs in"] C --> D["Google says OK"] D --> E["Your app gets token"] E --> F["User is logged in!"]
Quick Comparison
| Method | Best For | Security |
|---|---|---|
| API Key | Simple apps | โญโญ |
| JWT | Modern apps | โญโญโญ |
| OAuth | Login with social | โญโญโญโญ |
๐ ๏ธ Part 4: HTTP Methods for APIs
The Four Main Actions
Think of HTTP methods as verbs โ they tell the server what action you want:
graph TD A["HTTP Methods"] --> B["GET ๐"] A --> C["POST โ"] A --> D["PUT โ๏ธ"] A --> E["DELETE ๐๏ธ"] B --> F["Read data"] C --> G["Create new data"] D --> H["Update existing data"] E --> I["Remove data"]
GET โ โShow me!โ ๐
Used to read or fetch data. Like looking at a menu.
<?php
// GET /api/users
// Returns all users
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"]
];
echo json_encode($users);
}
?>
Key Point: GET should never change data!
POST โ โCreate this!โ โ
Used to create new things. Like placing an order.
<?php
// POST /api/users
// Creates a new user
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the sent data
$input = json_decode(
file_get_contents('php://input'),
true
);
// Create user (simplified)
$newUser = [
"id" => 3,
"name" => $input['name']
];
http_response_code(201); // Created!
echo json_encode([
"success" => true,
"user" => $newUser
]);
}
?>
PUT โ โUpdate this!โ โ๏ธ
Used to update existing things. Like changing your order.
<?php
// PUT /api/users/1
// Updates user with ID 1
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
$input = json_decode(
file_get_contents('php://input'),
true
);
// Update user (simplified)
$updatedUser = [
"id" => 1,
"name" => $input['name']
];
echo json_encode([
"success" => true,
"user" => $updatedUser
]);
}
?>
DELETE โ โRemove this!โ ๐๏ธ
Used to delete things. Like canceling an order.
<?php
// DELETE /api/users/1
// Deletes user with ID 1
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// Delete user (simplified)
http_response_code(200);
echo json_encode([
"success" => true,
"message" => "User deleted"
]);
}
?>
Complete Example: A Full Router
<?php
header("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
// Fetch users
echo json_encode(["action" => "read"]);
break;
case 'POST':
// Create user
echo json_encode(["action" => "create"]);
break;
case 'PUT':
// Update user
echo json_encode(["action" => "update"]);
break;
case 'DELETE':
// Delete user
echo json_encode(["action" => "delete"]);
break;
default:
http_response_code(405);
echo json_encode([
"error" => "Method not allowed"
]);
}
?>
๐ฏ Putting It All Together
Hereโs how everything connects:
graph TD A["๐ฑ Client App"] -->|HTTP Request| B["๐ API Endpoint"] B -->|Check| C["๐ Authentication"] C -->|Valid| D["Process Request"] C -->|Invalid| E["Return 401 Error"] D -->|GET/POST/PUT/DELETE| F["๐ฆ JSON Response"] F --> A
Real-World Flow
- Client sends request to
/api/users - Server checks the API key or token
- Server processes the request based on HTTP method
- Server returns JSON response
- Client displays the data
๐ก Key Takeaways
| Concept | Remember This |
|---|---|
| REST | Rules for building predictable APIs |
| JSON | Universal language for data |
| API Keys | Simple password for apps |
| JWT | Secure wristband with expiry |
| GET | Read data (never changes anything) |
| POST | Create new data |
| PUT | Update existing data |
| DELETE | Remove data |
๐ You Did It!
You now understand:
- โ How REST APIs work like a restaurant service
- โ How JSON is the universal language of APIs
- โ Three ways to keep your API secure
- โ The four main HTTP methods and when to use each
Next step: Practice building a simple API endpoint. Start with GET, then add POST, and youโll be an API developer before you know it! ๐
Remember: Every expert was once a beginner. Youโve taken a big step today! ๐
