Often, we want to work with a specific resource on the server. Let's imagine each restaurant has its own webpage. When a user navigates to that page, we need to fetch that specific restaurant's data. We could fetch all the restaurants (using the /restaurants
endpoint we created in the last lesson) but that would be wasteful. It's also not feasible, however, to create a new endpoint on our server for every resource in our database e.g.
app.get('/restaurant1', (req, res) => {...})
app.get('/restaurant2', (req, res) => {...})
// and so on...
When writing RESTful APIs (REST is the style of organising APIs that is most commonly used), the way we fetch a single resource within a set is by appending a /<id>
to the path that fetches the entire set. For example, if we want to fetch the data for the restaurant with id = 2
in our database, we would make a request to /restaurants/2
The /
character in a path represents nesting. It's almost like our applicaiton server is pretending that it's a static file server and has the restaurant data stored in a folder like this.
public
└── restaurants
├── 1
├── 2
├── 3
├── 4
└── 5
We call these variable sections of path route parameters. Within express, we indicate a route parameter by prefixing with a colon e.g. :id
as shown below.
app.get("/restaurants/:id", (req, res) => {
console.log(req.params);
});
Express takes each of the route parameters and puts them in the req.params
object. For example, if the server recieved a request like http://localhost:3000/resaurants/8
then req.params
would be
{ id: 8 }
Complete the app.get("/restaurants/:id", ...
above so that it gets that restaurant's data from the database and returns it as a JSON. You will find the findByPk method useful.
Modify this endpoint so that the JSON also includes the information for all the menus and menu-items that belong to that restaurant. You might find the include
option useful - you can see an example here.