Skip to main content
RESTful Principles
CHAPTER 19 Beginner

CRUD Operations in REST APIs

Updated: May 13, 2026
5 min read

# CHAPTER 19

CRUD Operations in REST APIs

1. Introduction

You have learned all the individual puzzle pieces of a REST API: URLs, Methods, Status Codes, JSON, Authentication, and Validation. Now, it is time to put the puzzle together. The vast majority of backend web development revolves around four basic actions: Create, Read, Update, and Delete (CRUD). In Chapter 19, we will map these operations directly to REST endpoints and review the complete lifecycle of a resource.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Map the four CRUD operations to their respective HTTP methods and URLs.
  • Understand the expected Request and Response payloads for each operation.
  • Design a complete, standardized set of endpoints for a single resource.
  • Identify the correct HTTP status codes for the success and failure of each CRUD action.

3. Beginner-Friendly Explanation

Imagine you are managing an address book.
  • Create: Writing a new person's details into a blank page. (POST)
  • Read: Flipping to a page to look at a person's phone number. (GET)
  • Update: Erasing an old phone number and writing down their new one. (PUT/PATCH)
  • Delete: Tearing the page out of the book entirely. (DELETE)

In REST, a "Resource" (like a User, a Product, or an Article) will almost always have these four operations associated with it.

4. Real-World Examples

Let's look at how a real company like Spotify might manage playlists using CRUD.
  • Create: POST /playlists (Creates a new playlist)
  • Read: GET /playlists/5 (Views playlist #5)
  • Update: PUT /playlists/5 (Changes the name of playlist #5)
  • Delete: DELETE /playlists/5 (Deletes playlist #5)

5. Detailed Code Examples

Here is a conceptual blueprint of how a single api.php file routes CRUD operations based on the HTTP Method.
php
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
<?php
header("Content-Type: application/json");
$method = $_SERVER[&#039;REQUEST_METHOD'];
$resourceId = $_GET[&#039;id'] ?? null;

switch ($method) {
    case &#039;POST':
        // CREATE
        // Logic: Read php://input, validate, INSERT into DB.
        http_response_code(201);
        echo json_encode(["message" => "Resource created", "id" => 101]);
        break;

    case &#039;GET':
        // READ
        if ($resourceId) {
            // Logic: SELECT * FROM table WHERE id = $resourceId
            echo json_encode(["data" => ["id" => $resourceId, "name" => "Item"]]);
        } else {
            // Logic: SELECT * FROM table (List view)
            echo json_encode(["data" => [ /* array of items */ ]]);
        }
        break;

    case &#039;PUT':
    case &#039;PATCH':
        // UPDATE
        if (!$resourceId) {
            http_response_code(400);
            echo json_encode(["error" => "ID required for update"]);
            break;
        }
        // Logic: Read php://input, UPDATE table WHERE id = $resourceId
        echo json_encode(["message" => "Resource updated successfully"]);
        break;

    case &#039;DELETE':
        // DELETE
        if (!$resourceId) {
            http_response_code(400);
            echo json_encode(["error" => "ID required for deletion"]);
            break;
        }
        // Logic: DELETE FROM table WHERE id = $resourceId
        http_response_code(204); // No Content
        break;
}
?>

6. Request/Response Examples

Let's trace the full lifecycle of a "Task" resource.

1. Create (POST /tasks):

  • Request: {"title": "Buy Milk"}
  • Response: 201 Created -> {"id": 1, "title": "Buy Milk", "status": "pending"}

2. Read (GET /tasks/1):

  • Request: Empty body
  • Response: 200 OK -> {"id": 1, "title": "Buy Milk", "status": "pending"}

3. Update (PUT /tasks/1):

  • Request: {"title": "Buy Milk", "status": "completed"}
  • Response: 200 OK -> {"id": 1, "title": "Buy Milk", "status": "completed"}

4. Delete (DELETE /tasks/1):

  • Request: Empty body
  • Response: 204 No Content (Empty response body)

7. HTTP Examples

The HTTP methods map perfectly to SQL commands:
  • POST -> INSERT INTO...
  • GET -> SELECT FROM...
  • PUT / PATCH -> UPDATE...
  • DELETE -> DELETE FROM...

8. JSON Examples

When reading a list of resources (GET /tasks), the JSON should be structured as an array, often wrapped in a data object to allow room for pagination metadata.
json
123456789
{
  "meta": {
    "total": 2
  },
  "data": [
    { "id": 1, "title": "Task 1" },
    { "id": 2, "title": "Task 2" }
  ]
}

9. Best Practices

  • Standardized Responses: Ensure that a GET /tasks/1 returns the exact same JSON structure for a task as a POST /tasks returns upon creation. Consistency is key.
  • Idempotency is crucial: Ensure your DELETE /tasks/1 can be clicked 5 times by a laggy client without crashing the server. If the record is already gone, simply return a 404 Not Found or a 204 No Content again.
  • Soft Deletes: For critical data, don't actually run a SQL DELETE. Instead, run an UPDATE that sets a deleted_at timestamp. The API then filters out any records where deleted_at IS NOT NULL.

10. Common Mistakes

  • Forgetting the ID on Updates/Deletes: A common beginner error is making a PUT /tasks request without an ID, causing the SQL query to accidentally update *every single task* in the database to the new values!
  • Returning HTML on errors: If your SQL query fails, make sure your PDO Exception is caught and returned as a JSON 500 Internal Server Error, rather than echoing a PHP fatal error screen.

11. Mini Exercises

  1. 1. Match the CRUD operation to the HTTP method:
  • Create -> ? (POST)
  • Read -> ? (GET)
  • Update -> ? (PUT/PATCH)
  • Delete -> ? (DELETE)

12. Coding Challenges

Challenge 1: Map out the exact 5 REST endpoints (Method + URL) required to create a full CRUD system for managing a movies resource. Don't forget the difference between fetching one movie vs a list of movies.

13. MCQs with Answers

Question 1

Which HTTP method and URL combination is correct for updating a specific user?

Question 2

What SQL command does a REST API POST request typically trigger?

Question 3

What is the standard HTTP status code for a successful DELETE operation that returns no JSON body?

14. Interview Questions

  • Q: Explain how CRUD operations map to HTTP methods in REST.
  • Q: What is a "Soft Delete," and how would you implement it in a REST API?
  • Q: Why is it important for the GET /resource/{id} response structure to match the POST /resource response structure?

15. FAQs

Q: Do I have to implement all 4 operations for every resource? A: No! Many resources are Read-Only. For example, an endpoint that returns the weather (GET /weather) will not have POST, PUT, or DELETE endpoints, because users cannot change the weather.

16. Summary

In Chapter 19, we consolidated our knowledge into the definitive CRUD pattern. We mapped Create to POST, Read to GET, Update to PUT/PATCH, and Delete to the DELETE method. We reviewed the entire lifecycle of a resource, understanding exactly what URLs, Methods, and Status Codes should be used at every step to build a professional, standardized API.

17. Next Chapter Recommendation

You now understand the architecture perfectly. It's time to build it for real. Proceed to Chapter 20: Building REST APIs with PHP where we will abandon theory and write production-ready PHP routing and controller logic.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·