codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

Ā© 2026 codingstuff.io. All rights reserved.

Built with ā¤ļø for developers everywhere

/
/
All Tutorials
🐘

PHP

54 / 56 topics
53API Development in PHP54REST API Basics55GraphQL in PHP56Consuming Web Services
Tutorials/PHP/REST API Basics
🐘PHP

REST API Basics

Updated 2026-04-20
3 min read

Introduction

In today's digital age, applications need to communicate with each other seamlessly. REST (Representational State Transfer) APIs are a popular way for different software systems to exchange data over the internet. This tutorial will introduce you to the basics of creating and consuming REST APIs using PHP.

What is REST?

REST is an architectural style that uses standard HTTP methods like GET, POST, PUT, DELETE, etc., to perform operations on resources. It follows a client-server architecture where clients request resources from servers and receive responses in various formats such as JSON or XML.

Key Principles of REST

  1. Client-Server Architecture: Separation of concerns between the client and server.
  2. Statelessness: Each request from a client to a server must contain all the information needed to understand and complete the request.
  3. Cacheability: Responses can be cached by clients or intermediate servers to improve performance.
  4. Uniform Interface: A consistent interface for accessing resources, often using standard HTTP methods.
  5. Layered System: Multiple layers of abstraction can exist between the client and server.

Setting Up Your Environment

Before we dive into creating a REST API in PHP, ensure you have the following:

  • PHP Installed: Version 7.4 or higher is recommended.
  • Web Server: Apache or Nginx.
  • Database: MySQL or any other database of your choice.
  • Composer: For managing dependencies.

Creating a Basic REST API

We'll create a simple REST API for managing users. This will include endpoints to get all users, get a single user by ID, create a new user, update an existing user, and delete a user.

Step 1: Set Up Your Project Structure

Create the following directory structure:

rest-api/
ā”œā”€ā”€ index.php
ā”œā”€ā”€ api/
│   ā”œā”€ā”€ User.php
ā”œā”€ā”€ models/
│   ā”œā”€ā”€ User.php
ā”œā”€ā”€ config/
│   ā”œā”€ā”€ database.php

Step 2: Configure Database Connection

In config/database.php, set up your database connection:

<?php

return [
    'host' => 'localhost',
    'dbname' => 'your_database_name',
    'username' => 'your_username',
    'password' => 'your_password'
];

Step 3: Create the User Model

In models/User.php, define a simple model to interact with the database:

<?php

class User {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getAllUsers() {
        $query = "SELECT * FROM users";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getUserById($id) {
        $query = "SELECT * FROM users WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function createUser($data) {
        $query = "INSERT INTO users (name, email) VALUES (:name, :email)";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':name', $data['name']);
        $stmt->bindParam(':email', $data['email']);
        return $stmt->execute();
    }

    public function updateUser($id, $data) {
        $query = "UPDATE users SET name = :name, email = :email WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->bindParam(':name', $data['name']);
        $stmt->bindParam(':email', $data['email']);
        return $stmt->execute();
    }

    public function deleteUser($id) {
        $query = "DELETE FROM users WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        return $stmt->execute();
    }
}

Step 4: Create the API Controller

In api/User.php, create a controller to handle API requests:

<?php

require_once '../config/database.php';
require_once '../models/User.php';

class UserController {
    private $userModel;

    public function __construct() {
        $dbConfig = require('../config/database.php');
        $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']}";
        $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
        $this->userModel = new User($pdo);
    }

    public function getAllUsers() {
        $users = $this->userModel->getAllUsers();
        return json_encode(['status' => 'success', 'data' => $users]);
    }

    public function getUserById($id) {
        $user = $this->userModel->getUserById($id);
        if ($user) {
            return json_encode(['status' => 'success', 'data' => $user]);
        } else {
            return json_encode(['status' => 'error', 'message' => 'User not found']);
        }
    }

    public function createUser() {
        $data = json_decode(file_get_contents("php://input"), true);
        if ($this->userModel->createUser($data)) {
            return json_encode(['status' => 'success', 'message' => 'User created successfully']);
        } else {
            return json_encode(['status' => 'error', 'message' => 'Failed to create user']);
        }
    }

    public function updateUser($id) {
        $data = json_decode(file_get_contents("php://input"), true);
        if ($this->userModel->updateUser($id, $data)) {
            return json_encode(['status' => 'success', 'message' => 'User updated successfully']);
        } else {
            return json_encode(['status' => 'error', 'message' => 'Failed to update user']);
        }
    }

    public function deleteUser($id) {
        if ($this->userModel->deleteUser($id)) {
            return json_encode(['status' => 'success', 'message' => 'User deleted successfully']);
        } else {
            return json_encode(['status' => 'error', 'message' => 'Failed to delete user']);
        }
    }
}

Step 5: Handle Requests in index.php

In index.php, route the requests to the appropriate controller methods:

<?php

header('Content-Type: application/json');

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);

require_once 'api/User.php';

$userController = new UserController();

switch ($uri[1]) {
    case 'users':
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            if (isset($uri[2])) {
                echo $userController->getUserById($uri[2]);
            } else {
                echo $userController->getAllUsers();
            }
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            echo $userController->createUser();
        }
        break;
    case 'update':
        if ($_SERVER['REQUEST_METHOD'] === 'PUT' && isset($uri[2])) {
            echo $userController->updateUser($uri[2]);
        }
        break;
    case 'delete':
        if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && isset($uri[2])) {
            echo $userController->deleteUser($uri[2]);
        }
        break;
    default:
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Endpoint not found']);
}

Testing Your API

You can test your API using tools like Postman or curl. Here are some examples:

Get All Users

curl -X GET http://localhost/rest-api/index.php/users

Get User by ID

curl -X GET http://localhost/rest-api/index.php/users/1

Create a New User

curl -X POST http://localhost/rest-api/index.php/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'

Update an Existing User

curl -X PUT http://localhost/rest-api/index.php/update/1 \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe", "email": "jane@example.com"}'

Delete a User

curl -X DELETE http://localhost/rest-api/index.php/delete/1

Best Practices

  1. Error Handling: Always handle errors gracefully and return meaningful error messages.
  2. Validation: Validate all incoming data to prevent SQL injection and other security issues.
  3. Authentication: Secure your API endpoints using authentication mechanisms like OAuth or JWT.
  4. Rate Limiting: Implement rate limiting to prevent abuse of your API.
  5. Documentation: Document your API endpoints clearly for developers who will use it.

Conclusion

This tutorial has covered the basics of creating a REST API in PHP. You've learned how to set up your environment, create models and controllers, handle HTTP requests, and test your API. By following these steps and best practices, you can build robust and secure APIs for your applications.


PreviousAPI Development in PHPNext GraphQL in PHP

Recommended Gear

API Development in PHPGraphQL in PHP