PHP Creating REST API

beginner
13 min

PHP Creating REST API

Welcome to the exciting world of PHP! In this tutorial, we'll learn how to create a REST API using PHP, perfect for beginners and intermediates. Let's dive in!

What is a REST API? 🎯

REST (Representational State Transfer) API is a set of rules that allows different software systems to communicate with each other over the internet. It's widely used for building web services for mobile apps, web applications, and IoT devices.

Why PHP for REST API? πŸ“

PHP is a popular server-side scripting language used in creating dynamic web pages. It's open-source, easy to learn, and has extensive community support, making it a great choice for building REST APIs.

Setting Up Our Environment πŸ’‘

Before we begin, ensure you have the following installed:

  1. PHP
  2. A web server (e.g., Apache or Nginx)
  3. PHP extension for handling JSON (e.g., json extension)

For this tutorial, we'll use the built-in PHP web server for simplicity.

Creating Our First REST API βœ…

We'll create a simple API to manage a list of books.

bash
// Create a file named books.php

Book Class πŸ“

Let's define a Book class to represent a book object.

php
// books.php class Book { public $title; public $author; public function __construct($title, $author) { $this->title = $title; $this->author = $author; } }

API Endpoints πŸ’‘

Now, let's create methods for the following API endpoints:

  1. GET /books: Retrieve all books
  2. POST /books: Add a new book
  3. GET /books/:id: Retrieve a specific book
  4. PUT /books/:id: Update a specific book
  5. DELETE /books/:id: Delete a specific book

Retrieving All Books πŸ“

php
// books.php // ... (Book class definition) $books = array(); // Add some sample books $books[] = new Book("Book 1", "Author 1"); $books[] = new Book("Book 2", "Author 2"); function getBooks() { global $books; return $books; }

Adding a New Book πŸ’‘

php
// books.php // ... (getBooks function) function addBook($title, $author) { global $books; $books[] = new Book($title, $author); }

Retrieving a Specific Book πŸ“

php
// books.php // ... (getBooks and addBook functions) function getBook($id) { global $books; foreach ($books as $book) { if ($book->id === $id) { return $book; } } return null; }

Updating a Specific Book πŸ’‘

php
// books.php // ... (getBook function) function updateBook($id, $title, $author) { global $books; foreach ($books as $key => $book) { if ($book->id === $id) { $books[$key] = new Book($title, $author); break; } } }

Deleting a Specific Book πŸ“

php
// books.php // ... (updateBook function) function deleteBook($id) { global $books; foreach ($books as $key => $book) { if ($book->id === $id) { unset($books[$key]); break; } } }

Handling API Requests πŸ’‘

Now, we'll handle the incoming requests using PHP's built-in $_SERVER superglobal array.

php
// books.php // ... (all functions above) if ($_SERVER["REQUEST_METHOD"] === "GET") { // Handle GET requests if (isset($_GET["id"])) { $book = getBook($_GET["id"]); echo json_encode($book ? $book : array("error" => "Book not found")); } else { echo json_encode(getBooks()); } } elseif ($_SERVER["REQUEST_METHOD"] === "POST") { // Handle POST requests $title = $_POST["title"]; $author = $_POST["author"]; addBook($title, $author); echo json_encode(array("message" => "Book added successfully")); } elseif ($_SERVER["REQUEST_METHOD"] === "PUT") { // Handle PUT requests $id = intval($_GET["id"]); $title = $_POST["title"]; $author = $_POST["author"]; updateBook($id, $title, $author); echo json_encode(array("message" => "Book updated successfully")); } elseif ($_SERVER["REQUEST_METHOD"] === "DELETE") { // Handle DELETE requests $id = intval($_GET["id"]); deleteBook($id); echo json_encode(array("message" => "Book deleted successfully")); } else { echo json_encode(array("error" => "Invalid request method")); }

Testing Our API πŸ’‘

Now that we have our API ready, let's test it using curl or a tool like Postman.

bash
// Using curl curl -X GET http://localhost/books curl -X POST -d 'title=Book 3&author=Author 3' http://localhost/books curl -X GET http://localhost/books/1

Next Steps πŸ“

Now you have a basic understanding of creating a REST API using PHP. You can further improve this API by:

  1. Implementing error handling
  2. Using a database to store the books
  3. Authenticating and authorizing requests

Quiz

Quick Quiz
Question 1 of 1

Why is PHP a good choice for creating REST APIs?