Building a REST API with PHP

Tutorial 1 of 5

1. Introduction

  • Goal of the tutorial: This tutorial aims to guide you in building a REST API using PHP. By the end of this tutorial, you will have a functional API that can handle CRUD (Create, Retrieve, Update, Delete) operations.
  • Learning outcomes: You will learn how to handle HTTP requests, connect to a MySQL database using PHP, and return responses in JSON format.
  • Prerequisites: Basic understanding of PHP, HTML, and MySQL. Familiarity with JSON format is also beneficial.

2. Step-by-Step Guide

  • Handling HTTP requests: PHP has built-in support for handling HTTP requests using the $_SERVER['REQUEST_METHOD'] variable. It allows you to determine whether the request was a GET, POST, PUT, or DELETE.
  • Connecting to a MySQL database: PHP's PDO extension provides a convenient way to interact with databases. You'll learn how to use it to connect to a MySQL database and execute queries.
  • Returning responses in JSON format: JSON is the standard format for sending and receiving data via a REST API. You'll learn how to convert PHP arrays to JSON using the json_encode() function.

3. Code Examples

  • Example 1: Connecting to a MySQL database
<?php
$host = 'localhost';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new PDO($dsn, $user, $pass);
?>

This code creates a new PDO instance, which represents a connection to a MySQL database.

  • Example 2: Handling a GET request
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $pdo->query('SELECT * FROM users');
    $users = $stmt->fetchAll();
    echo json_encode($users);
}
?>

This code checks if the request method is GET. If it is, it executes a SELECT query to fetch all users from the database. The results are then converted to JSON and sent back to the client.

4. Summary

In this tutorial, you learned how to build a REST API with PHP. You learned how to handle HTTP requests, connect to a MySQL database, and return responses in JSON format. To continue learning, you might want to explore how to handle PUT and DELETE requests and how to add authentication to your API.

5. Practice Exercises

  • Exercise 1: Modify the API to support returning a single user based on their ID.
  • Exercise 2: Add support for creating new users via a POST request.
  • Exercise 3: Add error handling to return appropriate HTTP status codes and messages when things go wrong.

Remember, practice is key in programming. Keep building, keep refining, and don't be afraid to experiment with your code.