create a basic api in php

First of all Make sure you have PHP and a web server like Apache or Nginx installed on your computer.

Create a Directory Structure:

Create a directory for your project. Inside this directory, create an index.php file and a folder for your API (e.g., api). The api folder will contain PHP files for each endpoint.

Create the index.php File:

<?php
header("Content-Type: application/json");

// Include the appropriate endpoint file based on the requested URL
$path = $_SERVER['REQUEST_URI'];
$path = explode('/', $path);

if ($path[1] === 'api' && isset($path[2])) {
    $endpoint = $path[2];
    $endpointFile = __DIR__ . "/api/{$endpoint}.php";

    if (file_exists($endpointFile)) {
        require_once $endpointFile;
    } else {
        http_response_code(404);
        echo json_encode(["message" => "Endpoint not found"]);
    }
} else {
    http_response_code(400);
    echo json_encode(["message" => "Invalid request"]);
}

Create API Endpoints:

Inside the api folder, create PHP files for each endpoint you want to create. For example, let’s create a simple hello.php endpoint that returns a JSON response.

<?php
// api/hello.php

$response = ["message" => "Hello, World!"];
echo json_encode($response);

Testing the API:

You can now access your API using URLs like http://localhost/api/hello in your web browser or by making HTTP requests using tools like cURL or Postman.

Example cURL request:

curl http://localhost/api/hello

You should receive a JSON response like:

{"message":"Hello, World!"}

This is a very basic example of creating an API in PHP.

About the author

Full-stack web developer with great knowledge of SEO & Digital Marketing. 7+ years of experience in Web Development.

Leave a Reply