CRUD Endpoints
Building an API
Preview
Full CRUD
List (GET)
function getCourses() {\n $stmt = $pdo->query("SELECT id, title, price FROM courses");\n return $stmt->fetchAll();\n}\n\nrespond(getCourses());One (GET by id)
function getCourse($id) {\n $stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");\n $stmt->execute([$id]);\n $row = $stmt->fetch();\n return $row ? $row : null;\n}\n\n$course = getCourse($id);\n$course ? respond($course) : respond(["error" => "Not found"], 404);Create (POST)
$required = ["title", "price"];\nforeach ($required as $f) {\n if (empty($input[$f])) {\n respond(["error" => "$f is required"], 422);\n }\n}\n$stmt = $pdo->prepare("INSERT INTO courses (title, price) VALUES (?, ?)");\n$stmt->execute([$input["title"], $input["price"]]);\nrespond(["id" => $pdo->lastInsertId()], 201);Update & delete (PUT/DELETE)
$stmt = $pdo->prepare("UPDATE courses SET title = ? WHERE id = ?");\n$stmt->execute([$input["title"], $id]);\n\n$stmt = $pdo->prepare("DELETE FROM courses WHERE id = ?");\n$stmt->execute([$id]);\nrespond(["deleted" => $stmt->rowCount() > 0]);Tip: Always use prepared statements. An API is the most exposed surface you will build — SQL injection there is devastating.
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.