1. Add CRUD Operations to Your Restaurants API
Build on your restaurants API from the Lesson 2 tasks by adding the missing CRUD operations. You should already have the GET endpoints working.
Add these new endpoints to your existing restaurants project
- Add express.json() middleware (if you don’t have it already).
- POST /restaurants - Create new restaurants (name, cuisine_type, rating required).
- PUT /restaurants/:id - Update entire restaurant (all fields required).
- PATCH /restaurants/:id - Update specific restaurant fields (at least one field required).
- DELETE /restaurants/:id - Remove a restaurant.
Follow the same patterns from this lesson: parameterised queries and error handling. Return the restaurant object when required.
2. Test Your Complete Restaurants CRUD API
Test all operations on your restaurants API:
Create and Read
- Create several restaurants with POST.
- List all restaurants with GET /restaurants.
- Get individual restaurants with GET /restaurants/:id.
Update Operations
- Use PUT to update name, cuisine_type, and rating.
- Use PATCH to update only name.
- Use PATCH to update only rating.
- Try updating non-existent restaurants (should return 404).
Delete Operations
- Delete a restaurant with DELETE.
- Try to get the deleted restaurant (should return 404).
- Try to delete a non-existent restaurant (should return 404).
3. Add Restaurant Validation
While we’ll cover proper validation in Module 3, let’s add some basic validation here to improve our endpoints and protect our database from invalid data.
Add validation specific to restaurant data:
function isValidRating(rating: number): boolean {
return rating >= 1 && rating <= 5;
}
function isValidName(name: string): boolean {
return name && name.length >= 2 && name.length <= 100;
}
function isValidCuisineType(cuisine: string): boolean {
return cuisine && cuisine.length >= 2 && cuisine.length <= 50;
}
Apply this validation in POST, PUT, and PATCH endpoints to ensure:
- Restaurant names are 2-100 characters.
- Cuisine types are 2-50 characters.
- Ratings are between 1 and 5.
4. Test All Validation Scenarios
Test your validation thoroughly:
Valid Data
- Create restaurants with proper name, cuisine, and rating.
- Update with valid partial data.
Invalid Data
- Missing required fields (should return 400).
- Invalid ratings (0, 6, negative numbers).
- Empty or too long names/cuisine types.
- Invalid restaurant IDs.
Make sure all validation errors return appropriate error messages.