Tying it all together – building a REST server

In this recipe, let's write at least a part of a complete RESTful server for our world database that we started using in the Working with a database section of the previous chapter, according to the routing scheme that we saw in the Adding Routes section earlier in this chapter. We'll focus on just working with Regions, but only for the sake of brevity; Countries and Cities are very similar in terms of coding, and the full code is provided with this book.

Our REST services will send JSON answers and require tokens for authorization. We will enable CORS so that we can access them from different web pages. The routes we will process will be as follows:

  • GET /regions will provide all regions of all countries
  • GET /regions/:country will return all regions of the given country
  • GET /regions/:country/:region will return a single region
  • DELETE /regions/:country/:region will let us delete a given region
  • POST /regions/:country will allow us to create a new region
  • PUT /regions/:country/:region will let us create or update a given region

Dealing with countries and cities is quite similar, with only a couple of exceptions:

  • Because of the size of the result set, we won't accept GET /cities requests to provide all cities in the world; only GET /cities/:city will be permitted. An alternative would be accepting the request, but sending back a 405 status code, Method not allowed.
  • Since country codes cannot be assigned at will, we won't allow POST /countries. Instead, PUT /countries/:country will be required to add a new country, as well as for updating an existing one.

Each type of request will produce the appropriate HTTP status codes; we'll see that in the following sections. Also, GET requests will be sent JSON results, and POST requests will be sent the location of the newly created entity; more on this later. 

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

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