Learn PHP · 13/14

Web Services and APIs

10 min read

markdown
Hello there! Welcome to the wonderful world of Web Services and APIs in PHP. Grab a cup of your favorite beverage ☕, and let's get ready to make our PHP applications talk to the rest of the internet.

### What's a Web Service, and Why Do We Need an API?

**The Problem:** Imagine your amazing PHP application has some cool data or functionality. For instance, maybe it can calculate the probability of a cat successfully landing on its feet from a given height. Now, a friend who's building a mobile app wants to use that calculation. How do you let their app "talk" to your app securely and efficiently? You can't just give them your database password. That would be a catastrophe! 🙀

**The Solution:** You create a **Web Service**, which is essentially a way for two machines to communicate over a network (like the internet). The "rules" for this communication, the specific language and commands they agree to use, are defined by an **API (Application Programming Interface)**.

Think of an API as a restaurant menu. The menu (the API) tells you what dishes you can order (what data/functionality is available), how to order them (the specific request format), and what you'll get back (the response). You don't need to know what's happening in the kitchen (the server's internal code); you just need to know how to use the menu.

---

### 1. Fetching Data from External APIs 🎣

Often, you'll want your application to consume data from someone else's API. Maybe you want to display the current weather, show the latest stock prices, or fetch a random dog picture.

#### a. The Simple Approach: `file_get_contents()`

`file_get_contents()` is a straightforward PHP function that can read the contents of a file into a string. As it turns out, it can also read from a URL!

**Under the Hood:** When you give it a URL, PHP makes a simple HTTP GET request to that URL and gives you back the raw response body as a string. It's like calling a phone number that has a pre-recorded message and just listening to it.

**Example: Getting a Random Fact About Cats**

Let's use a public API to get a random cat fact.

```php
<?php

// The URL of the API endpoint
$apiUrl = 'https://catfact.ninja/fact';

// Let's go get the data!
$jsonResponse = file_get_contents($apiUrl);

// It's a good practice to check if the request was successful
if ($jsonResponse === false) {
    die('Oops! Failed to fetch data from the API.');
}

// The API returns data in JSON format, so we need to decode it
// The 'true' argument converts the JSON object into a PHP associative array
$data = json_decode($jsonResponse, true);

// Check if decoding was successful
if ($data === null) {
    die('Oops! Failed to decode the JSON response.');
}

// Now, we can use the data!
echo "Here is a random cat fact for you:\n";
echo $data['fact'];

?>

Limitations: file_get_contents() is great for simple GET requests but falls short when you need more control. You can't easily set headers, use other HTTP methods (like POST), or handle timeouts gracefully.

b. The Powerful Way: cURL

Meet cURL (Client URL). It's the Swiss Army knife for making HTTP requests in PHP. It gives you immense control over every aspect of the request. If file_get_contents() is a bicycle, cURL is a fully-equipped spaceship. 🚀

The cURL Workflow: It's a simple four-step process:

  1. Initialize (curl_init): Create a new cURL handle.
  2. Set Options (curl_setopt): Tell cURL what you want to do (e.g., set the URL, ask for the result as a string, etc.).
  3. Execute (curl_exec): Send the request and get the response.
  4. Close (curl_close): Clean up the handle.

Example: Getting a Cat Fact with cURL

php
<?php

// The URL of the API endpoint
$apiUrl = 'https://catfact.ninja/fact';

// 1. Initialize a cURL session
$ch = curl_init();

// 2. Set options
// CURLOPT_URL: The URL we want to fetch
curl_setopt($ch, CURLOPT_URL, $apiUrl);

// CURLOPT_RETURNTRANSFER: This is important! It tells cURL to return
// the response as a string instead of just outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 3. Execute the cURL session
$jsonResponse = curl_exec($ch);

// Always a good idea to check for errors
if (curl_errno($ch)) {
    die('cURL Error: ' . curl_error($ch));
}

// 4. Close the cURL session
curl_close($ch);

// Just like before, we decode the JSON response
$data = json_decode($jsonResponse, true);

if ($data === null) {
    die('Oops! Failed to decode the JSON response.');
}

echo "And here's another fact, brought to you by cURL:\n";
echo $data['fact'];

?>

While it's a bit more code, cURL is the industry standard for its flexibility and power.


2. Building a Simple REST API with PHP 🛠️

Now, let's switch hats. Instead of getting data, we're going to provide it. We'll build a very basic REST API.

What is a REST API? REST (Representational State Transfer) is not a technology but a set of architectural principles for designing networked applications. It's a popular way to build APIs that are simple, scalable, and easy to understand.

Core Concepts:

  • Resources: Your API exposes "resources." A resource can be anything: a user, a product, a cat fact. Each resource is identified by a unique URL (e.g., /users/123).
  • HTTP Methods: We use standard HTTP methods to interact with these resources. The most common are:
    • GET: Retrieve a resource.
    • POST: Create a new resource.
    • PUT/PATCH: Update an existing resource.
    • DELETE: Remove a resource.

Example: A Simple "Users" API

Let's create a single api.php file that can handle a GET request to fetch a list of users.

php
<?php
// api.php

// This header tells the client that we are sending JSON data.
// It's very important!
header("Content-Type: application/json; charset=UTF-8");

// A little bit of "in-memory" data. In a real application,
// this would come from a database.
$users = [
    1 => ['name' => 'Alice', 'email' => '[email protected]'],
    2 => ['name' => 'Bob', 'email' => '[email protected]'],
    3 => ['name' => 'Charlie', 'email' => '[email protected]']
];

// Figure out what the client is asking for.
// We'll use the HTTP method.
$requestMethod = $_SERVER["REQUEST_METHOD"];

// Handle the request based on the method
switch ($requestMethod) {
    case 'GET':
        // For a GET request, we just send our list of users.
        // We set a success response code (200 OK).
        http_response_code(200);
        echo json_encode($users);
        break;
    
    // In a real app, you would add cases for POST, PUT, DELETE etc.
    // case 'POST':
    //    // ... code to create a new user ...
    //    break;

    default:
        // If the method is not supported, send a 405 Method Not Allowed response.
        http_response_code(405);
        echo json_encode(['message' => 'Method Not Allowed']);
        break;
}

?>

If you run this script on a server and navigate to your-server/api.php, you'll see the JSON output of your user data! You've just built an API endpoint. 🎉


3. Sending and Receiving JSON Data Appropriately ✉️

As you've seen, JSON (JavaScript Object Notation) is the universal language of modern APIs. It's lightweight, human-readable, and easy for computers to parse. PHP has excellent built-in functions for handling JSON.

The Problem: Your PHP application understands PHP arrays and objects. A JavaScript client understands JavaScript objects. How do they exchange data without getting confused?

The Solution: JSON acts as the perfect interpreter.

Encoding: From PHP to JSON with json_encode()

When your API sends a response, you take your PHP data (usually an associative array) and "encode" it into a JSON string.

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

$userProfile = [
    'id' => 101,
    'username' => 'php_dev',
    'isActive' => true,
    'tags' => ['api', 'php', 'json']
];

// Convert the PHP array into a JSON string
$jsonString = json_encode($userProfile, JSON_PRETTY_PRINT);
// JSON_PRETTY_PRINT makes the output human-readable. Good for debugging!

echo $jsonString;
?>

Decoding: From JSON to PHP with json_decode()

When your PHP application receives data from an API (or a POST request to your own API), you'll get a JSON string. You need to "decode" it back into a PHP variable.

php
<?php

// Imagine this is the JSON string you received from a POST request
$incomingJson = '{"productId":54321,"quantity":2,"customerNote":"Please gift wrap!"}';

// Decode the JSON string into a PHP associative array
// The 'true' argument is crucial for getting an array. Without it, you'd get a stdClass object.
$dataArray = json_decode($incomingJson, true);

// Now you can easily access the data
echo "Product ID: " . $dataArray['productId'] . "\n";
echo "Quantity: " . $dataArray['quantity'] . "\n";

// To get data from a POST request body:
// $jsonInput = file_get_contents('php://input');
// $postData = json_decode($jsonInput, true);

?>

4. Basic API Authentication Concepts 🔑

Your API is like an exclusive club. You don't want just anyone walking in. Authentication is the process of verifying who is making the request, ensuring they are who they say they are.

The Problem: How do you protect your API from unauthorized access, prevent abuse, and track who is using it?

The Solution: Require some form of credentials with each request.

a. API Keys

This is one of the simplest forms of authentication. You generate a unique, secret string of characters (the key) for each client. The client must include this key in every request they make.

How it works:

  • The client usually sends the key in an HTTP header, like X-API-Key.
  • Your API server code checks for this header.
  • It then checks if the provided key is valid (e.g., by looking it up in a database). If it's valid, the request proceeds. If not, it's rejected with a 401 Unauthorized or 403 Forbidden error.

Example: Protecting our API

Let's add a very simple key check to our api.php.

php
<?php
// api.php (updated)
header("Content-Type: application/json");

// Define our "secret" key. In a real app, this would not be hardcoded!
// You would have a list of valid keys in a database.
$validApiKey = "super-secret-key-12345";

// Check for the API key in the request headers
$providedApiKey = $_SERVER['HTTP_X_API_KEY'] ?? ''; // Using the null coalescing operator

if ($providedApiKey !== $validApiKey) {
    // Key is missing or incorrect, send a Forbidden response and stop.
    http_response_code(403);
    echo json_encode(['message' => 'Forbidden: Invalid API Key']);
    exit(); // Important to stop the script here!
}

// --- If we reach this point, the key was valid ---
// The rest of our API logic goes here...

$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod == 'GET') {
    $users = [
        1 => ['name' => 'Alice', 'email' => '[email protected]'],
        2 => ['name' => 'Bob', 'email' => '[email protected]']
    ];
    http_response_code(200);
    echo json_encode($users);
} else {
    http_response_code(405);
    echo json_encode(['message' => 'Method Not Allowed']);
}
?>

Funny but serious fact: Hardcoding secrets like API keys directly in your code is a huge security risk. It's like leaving your house key under the doormat with a big sign pointing to it. In the real world, you'd use environment variables or a secure secrets management system.

b. Tokens (e.g., Bearer Tokens)

Tokens are another common method, often used when you need to authenticate a specific user rather than just an application. A common flow is:

  1. A user logs in with a username/password.
  2. The server validates them and issues a temporary, encrypted token (like a JSON Web Token - JWT).
  3. The client then sends this token back with every subsequent request, usually in the Authorization header, like this: Authorization: Bearer <the-long-token-string>.
  4. The server validates the token on each request to identify and authorize the user.

This is a bit more advanced, but the principle is the same: the client presents a secret credential, and the server validates it.


Extra Reading & References

To dive deeper, the official PHP documentation is your best friend. It's concise, accurate, and has tons of examples.

Happy coding! You're now equipped to make your PHP applications connect with the vast world of web services. ✨

text

Challenge

You are tasked with creating a secure API endpoint in a single PHP script. This endpoint will process new user registrations.

Requirements:

  1. HTTP Method Validation: The script must strictly accept POST requests. If any other method (e.g., GET, PUT) is used, it must respond with a 405 Method Not Allowed status code and a JSON object: {"error": "Method Not Allowed"}.

  2. API Key Authentication: The script must require an API key for access. It must check for an X-API-Key HTTP header. If the header is missing or its value is not exactly SECRET_KEY_12345, it must respond with a 401 Unauthorized status code and a JSON object: {"error": "Unauthorized"}.

  3. Payload Processing:

    • The script must read the raw JSON payload from the request body.
    • The payload is expected to be a JSON object containing username and email keys.
    • If the payload is not valid JSON or if either the username or email key is missing, the script must respond with a 400 Bad Request status code and a JSON object: {"error": "Invalid or missing data"}.
  4. Successful Response:

    • If all validations pass, the script must set the HTTP response status code to 201 Created.
    • It must set the Content-Type header to application/json.
    • The response body must be a JSON object where status is "success" and data is an object containing a userId and the original username. The userId must be a string constructed by concatenating "user_" with a random integer between 1000 and 9999.

Expected result

Your code should be a single, complete PHP script that correctly implements all the requirements for the API endpoint.

The solution should demonstrate the following:

  • Use of $_SERVER['REQUEST_METHOD'] to check the request type.
  • Correctly setting the HTTP response status code for different scenarios using http_response_code().
  • Retrieving HTTP headers, specifically the X-API-Key, using functions like getallheaders() or by accessing the $_SERVER superglobal.
  • Reading the raw request body using the php://input stream wrapper with file_get_contents().
  • Parsing the incoming JSON string into a PHP associative array using json_decode().
  • Validating the structure and presence of keys in the decoded data.
  • Setting the Content-Type: application/json header using the header() function for all JSON responses.
  • Generating the final success or error JSON response string using json_encode() and outputting it.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.