Using routes

Routes are the magic behind our RESTful API. If you remember when we talked about HTTP verbs, RESTful is composed by combining CRUD operations with the HTTP verbs. Express.js makes easy the definition of these RESTful way. For example, open the server.js file and apply the following change:

...
app.get('/hello', (req, res) => {
res.send("Hello!")
})
...

As you can see, we changed use for get. As you are so smart, you know that get refers to the GET HTTP verb, so let's define our RESTful routes for our Teams API. In the server.jsapply the following changes:

...

app.get('/teams', (req, res) => {
res.send("To retrieve the list of teams")
})

app.post('/teams', (req, res) => {
res.send("To create a new team")
})

app.put('/teams', (req, res) => {
res.send("To update an existing team")
})

app.delete('/teams', (req, res) => {
res.send("To delete an existing team")
})

...

Once we apply these changes, it's time to test them. Run the following commands in your Terminal:

$ curl -X POST http://localhost:3000/teams
To create a new team

$ curl -X GET http://localhost:3000/teams
To retrieve the list of teams

Cool! our RESTful API is responding correctly. Note that we use the -X [HTTP Verb] to tell curl which HTTP verb we want to use for the given request. Now that we are ready with the main skeleton of our API, we need to structure our project in a consistent way because we will create a group of files and should always organize our source code. Keep reading!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset