We need to add functionality to our API to allow restaurants to be created, updated and deleted.
Let's start with creating a new restaurant. So far, we've only been using the GET HTTP method. However, when we create a resource, we should use POST instead. POST requests will typically include a body which contains the specifics of the data we want to create.
Let's first add the following two pieces of middleware so that Express can read JSON and URL encoded request bodies.
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
Then we need to create a new endpoint to listen for the POST requests. Because we've added that middleware, Express will place the HTTP request's body data in the req.body
object.
app.post('/restaurants', (req, res) => {
console.log(req.body);
// use the data in req.body to add a new restaurant to the database
res.sendStatus(201);
})
The sendStatus
methods is used to send back a specific status code. A 201 indicates a resource has been created. Also, notice how we just use the path /restaurants
rather than /createrestaurant
or something. The POST
signals that this endpoint is used for creating, the /restaurants
indicates what type of resource is being created.
To test the CRUD endpoints we're writing today, we can no longer just type URLs into our browser's search bar (this makes a GET request with no body). Fortunately, Postman allows you to choose which HTTP method your request will use and also add data to its body.
As you can see, there are many different ways to encode the body data. We're going to use x-www-form-urlencoded
. We can add key value pairs in the table below and these will get sent with the request and extracted into req.body
by Express.
Unlike creating a new restaurant, to delete a restuarant we'll need to specify a particular restaurant (think back to how we engineered this for GET-ing a restaurant). We'll also want to use the HTTP DELETE method. The Sequelize model's destroy method will help with this.
Updating is essentially a combination of deleting and creating so here we'll need to tell the endpoint both the id
of the restaurant we wish to update, as well as the new data we want it to have. When we're completely replacing a resource (as we are here) we use the HTTP PUT method. Sequelize models also have an update method.