Checkpoint 1: Routing
Last updated
Was this helpful?
Last updated
Was this helpful?
After installing the Flask package, let's read the and see what it wants us to do.
We find an example like the one below. Let's temporarily create a new file called "hello.py" in the root directory of the repo, and place the following contents inside:
NOTE: We are using a to specify the route (i.e. the path we visit in the browser).
NOTE: Flask route function names like
hello_world()
must be unique.
Later when we move and re-organize our application we'll need to run it differently, but for now with the "hello.py" file we can run it from the root directory like this:
NOTE: whenever we modify the code we'll need to stop the web server via "ctrl+c", and start it again before previewing again.
Let's add more routes.
After restarting the server, visit the following URLs in the browser:
Review the code that handles these "index" and "about" routes. What do you notice?
Nice, our app is handling requests to different routes!
Visit the following URLs in the browser, and notice we are now passing a URL parameter called "name" along with our requests:
FYI: the
%20
character acts as a space character in the URL params
Review the code that handles the "hello" route. Notice the "hello" route referencing the request
object from Flask, specifically looking at its args
property (i.e. request.args
), a dictionary-like object, to access the URL params.
Nice, our app is dynamically handling different URL parameters!
Finally, visit the following urls in the browser:
Review the code that handles these "book" routes. Notice how we are using the jsonify
method from Flask to convert a Python list or dictionary to a JSON response.
Wow, we've just made our own JSON API!
This command starts a local web server on port 5000. Preview the app by visiting in the browser. Nice, the web server is running and responding to our request.