ApiDrkDdl/Neu/api.php
2025-01-24 21:08:32 +01:00

79 lines
2.3 KiB
PHP

<?php
header("Content-Type: application/json");
include('config.php');
include('modules/Recipes.php');
include('modules/Comments.php');
include('modules/Ingredients.php');
include('modules/Users.php');
include('modules/MasterData.php');
// Funktion zur API-Key-Validierung
function validate_api_key() {
$headers = getallheaders();
$api_key = $headers['X-API-KEY'] ?? null; // Prüfe den `X-API-KEY` Header
if ($api_key !== API_KEY) {
http_response_code(403); // Forbidden
echo json_encode(["error" => "Ungültiger oder fehlender API-Key"]);
exit;
}
}
// Prüfe den API-Key
validate_api_key();
// Holen des Endpunkts und der Methode
$request_method = $_SERVER['REQUEST_METHOD'];
$uri = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
$endpoint = $uri[0] ?? null;
$id = $uri[1] ?? null;
switch ($request_method) {
case 'GET':
if ($endpoint === 'recipes') {
if ($id) {
echo get_recipe_by_id($id);
} else {
echo get_all_recipes();
}
} elseif ($endpoint === 'recipes' && isset($id) && is_numeric($id) && $uri[2] === 'comments') {
echo get_comments_by_recipe($id);
} else {
echo json_encode(["error" => "Ungültiger Endpunkt"]);
}
break;
case 'POST':
if ($endpoint === 'recipes') {
echo create_recipe();
} elseif ($endpoint === 'recipes' && isset($id) && is_numeric($id) && $uri[2] === 'comments') {
echo create_comment($id);
} else {
echo json_encode(["error" => "Ungültiger Endpunkt"]);
}
break;
case 'PUT':
if ($endpoint === 'recipes' && isset($id) && is_numeric($id)) {
echo update_recipe($id);
} else {
echo json_encode(["error" => "Ungültiger Endpunkt"]);
}
break;
case 'DELETE':
if ($endpoint === 'recipes' && isset($id) && is_numeric($id)) {
echo delete_recipe($id);
} elseif ($endpoint === 'comments' && isset($id) && is_numeric($id)) {
echo delete_comment($id);
} else {
echo json_encode(["error" => "Ungültiger Endpunkt"]);
}
break;
default:
echo json_encode(["error" => "Ungültige Anforderung"]);
break;
}
?>