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
*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 usefilegetcontents("php://input") to read it.
api/create_user.php
php
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. A React developer builds a frontend app.
-
2.
The React app sends an HTTP GET request to your
api/users.phpendpoint.
-
3.
Your PHP script connects to MySQL, fetches the users, and
jsonencode()s the result.
- 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.comfrom sending data to a website onfrontend.comfor 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. 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.