🛠️ CRUD Controllers and RESTful API Design

In this lesson, we'll implement all the CRUD operations for our API resources. We'll explore how REST principles map HTTP verbs and routes to controller functions, creating a predictable and intuitive API interface.


Understanding CRUD Operations

CRUD is the foundation of most APIs - four basic operations that can be performed on any resource:

Operation Purpose HTTP Verb Typical Route Status Code
Create Add new resource POST /api/resources 201 Created
Read Fetch resource(s) GET /api/resources or /api/resources/:id 200 OK
Update Modify resource PUT/PATCH /api/resources/:id 200 OK
Delete Remove resource DELETE /api/resources/:id 200 OK or 204 No Content

RESTful Route Design

REST (Representational State Transfer) provides conventions for API design:

<aside> 🎯

REST Principles:

Route + Verb = Controller Function

// The router literally maps verb + path to a function
router.get('/habits', getUserHabits)        // GET /api/habits
router.get('/habits/:id', getHabitById)     // GET /api/habits/123
[router.post](<http://router.post>)('/habits', createHabit)         // POST /api/habits
router.put('/habits/:id', updateHabit)      // PUT /api/habits/123
router.delete('/habits/:id', deleteHabit)   // DELETE /api/habits/123

HTTP Status Codes

Status codes communicate the result of an operation:

2xx Success

4xx Client Errors

5xx Server Errors


Habit Controller Implementation

<aside> 📝

File: src/controllers/habitController.ts

</aside>

Create Habit (POST)