API Development

Back

Loading concept...

๐Ÿš€ 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

  1. Stateless โ€“ Each request is independent (like ordering fresh each time)
  2. Client-Server โ€“ Separation of concerns (kitchen doesnโ€™t care who ordered)
  3. 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 &amp; 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

  1. Client sends request to /api/users
  2. Server checks the API key or token
  3. Server processes the request based on HTTP method
  4. Server returns JSON response
  5. 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! ๐ŸŽ‰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.