Given our database consists of a bunch of cafes to remote-work from, one of the likely use cases of our API is a developer who wants to serve up a random cafe for their user to go to. So let's create a /random route that serves up a random cafe.
1. Create a /random
route in main.py that allows GET requests to be made to it.
2. When someone makes a GET
request to the /random
route, our Flask server should fetch a random cafe from our database.
NOTE: Don't worry about returning anything at the moment.
Normally, we've been returning HTML templates using render_template(), but this time, because our server is now acting as an API, we want to return a JSON containing the necessary data. Just like real public APIs.
e.g. ISS API: http://api.open-notify.org/iss-now.json
In order to do this, we have to turn our random_cafe SQLAlchemy Object into a JSON. This process is called serialization.
Flask has a serialisation helper method built-in called jsonify()
. But we have to provide the structure of the JSON to return.
3. See if you can use the documentation on jsonify() to figure out how to get the /random
route to work. If successful, this is what you should see when you run main.py and go to localhost:5000/random
The method described in the docs has maximum flexibility. It allows you to have perfect control over the JSON response. e.g. You could also structure the response by omitting some properties like id
. You could also group the Boolean properties into a subsection called amenities.
But in most cases, you might just want to return all the data you have on a particular record and it would drive you crazy if you had to write out all that code for every route.
So another method of serialising our database row Object to JSON is by first converting it to a dictionary and then using jsonify() to convert the dictionary (which is very similar in structure to JSON) to a JSON.