Course API Development

Project Setup & Routing

Building an API Preview

An API in PHP

The entry point

// public/index.php\nheader("Content-Type: application/json");\n\n$method = $_SERVER["REQUEST_METHOD"];\n$uri    = trim($_SERVER["REQUEST_URI"], "/");\n$parts  = explode("/", $uri);

A simple router

$resource = $parts[1] ?? null;   // courses\n$id       = $parts[2] ?? null;\n\nif ($resource === "courses") {\n  switch ($method) {\n    case "GET":\n      echo json_encode($id ? getCourse($id) : getCourses());\n      break;\n    case "POST":\n      echo json_encode(createCourse());\n      break;\n  }\n}

Reading the body

$json  = file_get_contents("php://input");\n$input = json_decode($json, true);\n\nif (!is_array($input)) {\n  http_response_code(400);\n  echo json_encode(["error" => "Invalid JSON"]);\n  exit;\n}

Sending JSON responses

function respond($data, $code = 200) {\n  http_response_code($code);\n  echo json_encode($data);\n  exit;\n}\n\nrespond(["courses" => $rows]);\nrespond(["error" => "Not found"], 404);
Tip: Send Content-Type: application/json on every response — without it, clients may misread your data.

This is a free preview lesson

Enroll in the API Development to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.


Discussion

Free preview lesson