Skip to main content
PHP Backend Development Tutorial
CHAPTER 12 Beginner

Building REST APIs with PHP

Updated: May 14, 2026
25 min read

# CHAPTER 12

Building REST APIs with PHP

1. Introduction

So far, our backend has been generating HTML pages. This is perfect for a web browser, but what if you are building an iOS or Android app? Mobile apps do not want HTML; they just want raw data so they can draw their own interfaces. To solve this, backend developers build APIs (Application Programming Interfaces). In this chapter, we will learn how to turn our PHP application into a REST API that communicates entirely in JSON.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what an API is and why REST is the industry standard.
  • Understand how to output JSON data from PHP.
  • Build an API endpoint that handles HTTP GET and POST requests.
  • Test an API using a tool like Postman.

3. Beginner-Friendly Explanation

Imagine a restaurant (your database). If a customer walks in, you hand them a plated meal (an HTML webpage). But what if the customer is an UberEats driver? The driver doesn't want a plate; they want the raw food packed in a standardized cardboard box so they can deliver it elsewhere. An API is the takeout window. Instead of sending a beautiful HTML page, an API packages the raw database data into a standardized text format (called JSON) and sends it. A mobile app (the driver) receives the JSON box, unpacks the data, and displays it to the user on their phone.

4. What is REST and JSON?

  • REST (Representational State Transfer): A set of rules for building APIs. It dictates that APIs should use standard HTTP methods (GET to read data, POST to create data).
  • JSON (JavaScript Object Notation): The universal language of APIs. It is a lightweight text format that looks exactly like a PHP Associative Array. Every programming language on Earth knows how to read JSON.

5. Setting Up an API Endpoint (Outputting JSON)

To build an API, we create a PHP file that outputs JSON instead of HTML. We must tell the receiving computer what type of data is coming using HTTP Headers.

api/users.php

php
12345678910111213141516
<?php
// Tell the client that this page will return JSON, not HTML
header("Content-Type: application/json");

require &#039;../db.php';

// Fetch users from the database
$stmt = $pdo->query("SELECT id, name, email FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Convert the PHP Array into a JSON string and output it
echo json_encode([
    "status" => "success",
    "data" => $users
]);
?>

*If you visit this URL in your browser, you won't see a website. You will see a wall of raw JSON text.*

6. Handling POST Requests in an API

APIs don't use standard HTML forms to receive data. They receive raw JSON in the body of the HTTP request. We must use filegetcontents("php://input") to read it.

api/create_user.php

php
123456789101112131415161718192021222324252627
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");

require &#039;../db.php';

// Check if the request is actually a POST request
if ($_SERVER[&#039;REQUEST_METHOD'] == 'POST') {
    
    // Read the raw JSON sent by the mobile app or frontend framework
    $raw_json = file_get_contents("php://input");
    
    // Convert the JSON string into a PHP Associative Array
    $data = json_decode($raw_json, true);
    
    $name = $data[&#039;name'];
    $email = $data[&#039;email'];
    
    // Insert into database (Assume prepared statements are used here)
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    
    if ($stmt->execute([$name, $email])) {
        // Send a success response back to the client
        echo json_encode(["message" => "User created successfully"]);
    }
}
?>

7. Testing APIs with Postman

You cannot test a POST API easily in a web browser. Professional developers use a free software tool called Postman. Postman allows you to type in your API URL (http://localhost/api/createuser.php), select "POST", type a fake JSON payload, and hit "Send" to see how your PHP script reacts.

8. Backend Workflow: API Integration

  1. 1. A React developer builds a frontend app.
  1. 2. The React app sends an HTTP GET request to your api/users.php endpoint.
  1. 3. Your PHP script connects to MySQL, fetches the users, and jsonencode()s the result.
  1. 4. The React app receives the JSON, loops through it, and renders a beautiful UI list on the screen.

9. Best Practices

  • CORS (Cross-Origin Resource Sharing): By default, browsers block an API on api.com from sending data to a website on frontend.com for security reasons. You must add CORS Headers (header("Access-Control-Allow-Origin: *");) to your API to explicitly allow other domains to read your data.

10. Common Mistakes

  • Echoing Errors in an API: If a database connection fails and you use echo "Database Error"; in an API file, it will break the application. The mobile app is expecting JSON, not a plain text string! You must always return errors formatted as JSON: echo jsonencode(["status" => "error", "message" => "Database failed"]);.

11. Exercises

  1. 1. Explain the difference in output format between a standard PHP web page and a PHP REST API endpoint.

12. Coding Challenges

  • Challenge: Create an API endpoint called api/product.php?id=1. The script should check $GET['id'], find the product in a simulated array, and return the product details as JSON.

13. MCQs with Answers

Question 1

What is the standard data format used by modern REST APIs to transmit data between a backend server and a client application (like a mobile app)?

Question 2

When a mobile app sends a JSON payload to a PHP API via a POST request, how does PHP read that raw JSON data?

14. Interview Questions

  • Q: Explain the purpose of a REST API. Why would a company build an API rather than just serving HTML pages directly from their backend?
  • Q: Describe how you would handle an incoming POST request in a PHP API that contains a JSON payload. What functions are required to parse it?

15. FAQs

Q: I am building a website using React/Vue.js. Do I need an API? A: Yes! Modern frontend frameworks like React and Vue are "client-side" only. They cannot talk to a database. You must build a PHP REST API. The React frontend will make HTTP requests to your PHP backend, fetch the JSON data, and render it.

16. Summary

In Chapter 12, we decoupled our backend from our frontend. By building a REST API, our PHP application is no longer restricted to generating web pages. By speaking the universal language of JSON, our backend can now serve data to iPhones, Androids, smartwatches, and modern Javascript frameworks, acting as the central nervous system for an entire ecosystem of applications.

17. Next Chapter Recommendation

Currently, every API endpoint requires its own physical .php file. This gets messy. Proceed to Chapter 13: Routing and URL Management to learn how to create clean, professional URLs.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·