CRUD Operations with REST APIs

REST APIs are the backbone of modern web applications, providing a standardized way to interact with resources. CRUD operations—Create, Read, Update, and Delete—form the fundamental actions you can perform on these resources. This guide will walk you through implementing CRUD operations in a REST API.

What is CRUD?

REST API Principles

REST (Representational State Transfer) is an architectural style that uses HTTP methods to perform operations on resources. Key characteristics include:

Implementing CRUD Operations

1. Create (POST)

POST /api/resources HTTP/1.1

Host: example.com
Content-Type: application/json
{ "name": "New Resource",
"description": "This is a new resource" }

Best practices:

# response

HTTP/1.1 201 Created

Location: /api/resources/123
Content-Type: application/json
{ "id": 123,
"name": "New Resource",
"description": "This is a new resource" }

2. Read (GET)

# read collection

GET /api/resources HTTP/1.1

Host: example.com

# read single resource

GET /api/resources/123 HTTP/1.1

Host: example.com

# response

HTTP/1.1 200 OK

Content-Type: application/json

{ "id": 123,
"name": "Resource 1",
"description": "Details about resource 1" }

Best practices:

3. Update

Full Update (PUT)

PUT /api/resources/123 HTTP/1.1

Host: example.com
Content-Type: application/json

{ "name": "Updated Resource",
"description": "This resource has been updated" }

# response

HTTP/1.1 200 OK

Content-Type: application/json

{ "id": 123,
"name": "Updated Resource",
"description": "This resource has been updated" }

Partial Update(PATCH)

PATCH /api/resources/123 HTTP/1.1

Host: example.com
Content-Type: application/json

{ "description": "Only updating this field" }

# response

HTTP/1.1 200 OK

Content-Type: application/json

{ "id": 123,
"name": "Updated Resource",
"description": "Only updating this field" }

Best practices:

4. Delete (DELETE)

DELETE /api/resources/123 HTTP/1.1

Host: example.com

# response

HTTP/1.1 204 No Content

Best practices: