Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

RESTful APIs Tutorial

Introduction to RESTful APIs

RESTful APIs (Representational State Transfer) are a type of web service that follows the principles of REST. They are commonly used for building web services that are lightweight, scalable, and maintainable.

RESTful APIs use standard HTTP methods, such as GET, POST, PUT, and DELETE, to perform CRUD (Create, Read, Update, Delete) operations.

Setting Up Your Environment

To create a RESTful API with PHP, you'll need to have a web server with PHP installed. You can use XAMPP, WAMP, or any other PHP development environment. Make sure you have a basic understanding of PHP and MySQL.

Creating a Simple RESTful API

Let's create a simple RESTful API to manage a list of books. We'll use a MySQL database to store the data.

Step 1: Create the Database

Create a database named restful_api and a table named books with the following SQL query:

CREATE DATABASE restful_api;
USE restful_api;

CREATE TABLE books (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    author VARCHAR(255) NOT NULL,
    published_date DATE
);

Step 2: Connect to the Database

Create a file named db.php to handle the database connection:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "restful_api";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Step 3: Create the API Endpoints

Create a file named api.php to handle the API requests:

<?php
header("Content-Type: application/json");
include 'db.php';

$request_method = $_SERVER["REQUEST_METHOD"];

switch ($request_method) {
    case 'GET':
        if (!empty($_GET["id"])) {
            $id = intval($_GET["id"]);
            get_books($id);
        } else {
            get_books();
        }
        break;
    case 'POST':
        insert_book();
        break;
    case 'PUT':
        $id = intval($_GET["id"]);
        update_book($id);
        break;
    case 'DELETE':
        $id = intval($_GET["id"]);
        delete_book($id);
        break;
    default:
        header("HTTP/1.0 405 Method Not Allowed");
        break;
}

function get_books($id = 0)
{
    global $conn;
    $query = "SELECT * FROM books";
    if ($id != 0) {
        $query .= " WHERE id=" . $id . " LIMIT 1";
    }
    $response = array();
    $result = $conn->query($query);
    while ($row = $result->fetch_assoc()) {
        $response[] = $row;
    }
    echo json_encode($response);
}

function insert_book()
{
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    $title = $data["title"];
    $author = $data["author"];
    $published_date = $data["published_date"];
    $query = "INSERT INTO books SET title='$title', author='$author', published_date='$published_date'";
    if ($conn->query($query) === TRUE) {
        $response = array('status' => 1, 'status_message' => 'Book Added Successfully.');
    } else {
        $response = array('status' => 0, 'status_message' => 'Book Addition Failed.');
    }
    echo json_encode($response);
}

function update_book($id)
{
    global $conn;
    $data = json_decode(file_get_contents('php://input'), true);
    $title = $data["title"];
    $author = $data["author"];
    $published_date = $data["published_date"];
    $query = "UPDATE books SET title='$title', author='$author', published_date='$published_date' WHERE id=$id";
    if ($conn->query($query) === TRUE) {
        $response = array('status' => 1, 'status_message' => 'Book Updated Successfully.');
    } else {
        $response = array('status' => 0, 'status_message' => 'Book Update Failed.');
    }
    echo json_encode($response);
}

function delete_book($id)
{
    global $conn;
    $query = "DELETE FROM books WHERE id=$id";
    if ($conn->query($query) === TRUE) {
        $response = array('status' => 1, 'status_message' => 'Book Deleted Successfully.');
    } else {
        $response = array('status' => 0, 'status_message' => 'Book Deletion Failed.');
    }
    echo json_encode($response);
}
?>

Testing the API

Use tools like Postman or cURL to test your API. Below are some example requests:

GET all books

GET http://localhost/api.php

GET a single book by ID

GET http://localhost/api.php?id=1

POST a new book

POST http://localhost/api.php
Content-Type: application/json

{
    "title": "New Book",
    "author": "John Doe",
    "published_date": "2023-01-01"
}

PUT to update a book

PUT http://localhost/api.php?id=1
Content-Type: application/json

{
    "title": "Updated Book",
    "author": "Jane Doe",
    "published_date": "2023-01-02"
}

DELETE a book

DELETE http://localhost/api.php?id=1

Conclusion

In this tutorial, we've covered the basics of creating a RESTful API using PHP. We've set up a database, created endpoints for CRUD operations, and tested the API. This is just a starting point, and there are many ways to extend and improve your API, such as adding authentication, validation, and error handling.