Init
This commit is contained in:
91
index.php
Normal file
91
index.php
Normal file
@ -0,0 +1,91 @@
|
||||
<?php
|
||||
header('Content-Type: application/json');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
||||
|
||||
// Handle preflight OPTIONS requests
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit();
|
||||
}
|
||||
|
||||
require_once 'TodoController.php';
|
||||
|
||||
$controller = new TodoController();
|
||||
|
||||
// Get the request URI and method
|
||||
$request_uri = $_SERVER['REQUEST_URI'];
|
||||
$request_method = $_SERVER['REQUEST_METHOD'];
|
||||
|
||||
// Remove query string if present
|
||||
$path = strtok($request_uri, '?');
|
||||
|
||||
// Remove trailing slash if present
|
||||
$path = rtrim($path, '/');
|
||||
|
||||
// If path is empty, set to root
|
||||
if (empty($path)) {
|
||||
$path = '/';
|
||||
}
|
||||
|
||||
// Route handling
|
||||
switch ($path) {
|
||||
case '/':
|
||||
// Base route - show available endpoints
|
||||
if ($request_method === 'GET') {
|
||||
$host = $_SERVER['HTTP_HOST'];
|
||||
$port = $_SERVER['SERVER_PORT'];
|
||||
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
|
||||
|
||||
echo json_encode([
|
||||
'message' => "Todo API running at {$protocol}://{$host}:{$port}/",
|
||||
'available_endpoints' => [
|
||||
'GET /todos - Get all todos',
|
||||
'POST /todos - Create todo',
|
||||
'PUT /todos/:id - Update todo',
|
||||
'DELETE /todos/:id - Delete todo'
|
||||
]
|
||||
], JSON_PRETTY_PRINT);
|
||||
} else {
|
||||
http_response_code(405);
|
||||
echo json_encode(['error' => 'Method not allowed']);
|
||||
}
|
||||
break;
|
||||
|
||||
case '/todos':
|
||||
switch ($request_method) {
|
||||
case 'GET':
|
||||
$controller->getAllTodos();
|
||||
break;
|
||||
case 'POST':
|
||||
$controller->createTodo();
|
||||
break;
|
||||
default:
|
||||
http_response_code(405);
|
||||
echo json_encode(['error' => 'Method not allowed']);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Handle /todos/:id routes
|
||||
if (preg_match('/^\/todos\/(\d+)$/', $path, $matches)) {
|
||||
$id = (int)$matches[1];
|
||||
|
||||
switch ($request_method) {
|
||||
case 'PUT':
|
||||
$controller->updateTodo($id);
|
||||
break;
|
||||
case 'DELETE':
|
||||
$controller->deleteTodo($id);
|
||||
break;
|
||||
default:
|
||||
http_response_code(405);
|
||||
echo json_encode(['error' => 'Method not allowed']);
|
||||
}
|
||||
} else {
|
||||
http_response_code(404);
|
||||
echo json_encode(['error' => 'Endpoint not found']);
|
||||
}
|
||||
}
|
||||
?>
|
Reference in New Issue
Block a user