Создание REST API в PHP

Активный
Статус
Сообщения
516
Лайки
32

8

месяц на сайте

REST API позволяет взаимодействовать с приложением через HTTP. Разберем создание API.

Базовая структура API
Код:
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type");

// Получение метода запроса
$method = $_SERVER["REQUEST_METHOD"];
$path = $_SERVER["PATH_INFO"] ?? "/";

// Роутинг
switch($method) {
    case "GET":
        handleGet($path);
        break;
    case "POST":
        handlePost($path);
        break;
    case "PUT":
        handlePut($path);
        break;
    case "DELETE":
        handleDelete($path);
        break;
    default:
        http_response_code(405);
        echo json_encode(["error" => "Method not allowed"]);
}

function handleGet($path) {
    if($path == "/users") {
        getUsers();
    } elseif(preg_match("/\/users\/(\d+)/", $path, $matches)) {
        getUser($matches[1]);
    } else {
        http_response_code(404);
        echo json_encode(["error" => "Not found"]);
    }
}

function getUsers() {
    // Получение пользователей из БД
    $users = [
        ["id" => 1, "name" => "John", "email" => "john@example.com"],
        ["id" => 2, "name" => "Jane", "email" => "jane@example.com"]
    ];
    
    echo json_encode($users);
}

function getUser($id) {
    // Получение пользователя по ID
    $user = ["id" => $id, "name" => "John", "email" => "john@example.com"];
    echo json_encode($user);
}
?>

Обработка POST запросов
Код:
<?php
function handlePost($path) {
    if($path == "/users") {
        createUser();
    } else {
        http_response_code(404);
        echo json_encode(["error" => "Not found"]);
    }
}

function createUser() {
    $data = json_decode(file_get_contents("php://input"), true);
    
    // Валидация
    if(!isset($data["name"]) || !isset($data["email"])) {
        http_response_code(400);
        echo json_encode(["error" => "Missing required fields"]);
        return;
    }
    
    // Создание пользователя
    $user = [
        "id" => uniqid(),
        "name" => $data["name"],
        "email" => $data["email"]
    ];
    
    http_response_code(201);
    echo json_encode($user);
}
?>

Класс API
Код:
<?php
class API {
    private $routes = [];
    
    public function get($path, $callback) {
        $this->routes["GET"][$path] = $callback;
    }
    
    public function post($path, $callback) {
        $this->routes["POST"][$path] = $callback;
    }
    
    public function put($path, $callback) {
        $this->routes["PUT"][$path] = $callback;
    }
    
    public function delete($path, $callback) {
        $this->routes["DELETE"][$path] = $callback;
    }
    
    public function run() {
        header("Content-Type: application/json");
        
        $method = $_SERVER["REQUEST_METHOD"];
        $path = $_SERVER["PATH_INFO"] ?? "/";
        
        if(isset($this->routes[$method][$path])) {
            $callback = $this->routes[$method][$path];
            $callback();
        } else {
            http_response_code(404);
            echo json_encode(["error" => "Not found"]);
        }
    }
}

// Использование
$api = new API();

$api->get("/users", function() {
    echo json_encode(["users" => []]);
});

$api->get("/users/:id", function($id) {
    echo json_encode(["id" => $id]);
});

$api->run();
?>

Аутентификация
Код:
<?php
function authenticate() {
    $headers = getallheaders();
    
    if(!isset($headers["Authorization"])) {
        http_response_code(401);
        echo json_encode(["error" => "Unauthorized"]);
        exit;
    }
    
    $token = str_replace("Bearer ", "", $headers["Authorization"]);
    
    // Проверка токена
    if(!validateToken($token)) {
        http_response_code(401);
        echo json_encode(["error" => "Invalid token"]);
        exit;
    }
}

function validateToken($token) {
    // Проверка токена в БД
    return true; // упрощенная версия
}
?>

Обработка ошибок
Код:
<?php
function sendError($code, $message) {
    http_response_code($code);
    echo json_encode(["error" => $message]);
    exit;
}

function sendSuccess($data) {
    echo json_encode(["success" => true, "data" => $data]);
}

// Использование
try {
    // код
    sendSuccess($result);
} catch(Exception $e) {
    sendError(500, $e->getMessage());
}
?>

Важные моменты:
- Используйте правильные HTTP методы
- Возвращайте корректные коды ответов
- Валидируйте входные данные
- Реализуйте аутентификацию

REST API упрощает интеграцию с другими системами!
 

1 человек читают эту тему (Всего: 1, Пользователей: 0, Гостей: 1)

Сверху