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.
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 |
REST (Representational State Transfer) provides conventions for API design:
<aside> 🎯
REST Principles:
/api/habits
represents the habits collection// 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
Status codes communicate the result of an operation:
<aside> 📝
File: src/controllers/habitController.ts
</aside>