Expanding and Using Flask App
00:00 Expanding and Using the Flask App In the previous section of the course, you created your basic Flask REST API, which returned a JSON unified version of the data requested but most of the time you can just return a Python dictionary from a Flask function.
00:15 Flask will automatically convert any Python dictionary to JSON. The function you can see on screen will demonstrate this.
00:33
If you visit the country endpoint, you should see something similar to what’s seen on screen here. You return the second dictionary from countries
.
00:42
Flask will convert this dictionary to JSON and here’s what you should see. This is the JSON version of the dictionary you return from get_country()
.
00:52
Now you can try sending a POST request to add a country. You can do this in your shell using the command-line tool curl
. It allows you to send HTTP requests from the command line.
01:04 Here you’ll add a new country to the list of countries.
01:12
The curl
command has some options that are useful to know. -X
sets the HTTP method for the request. -H
adds an HTTP header to the request.
01:27
-d
defines the request data.
01:37
With these options set, curl
sends JSON data in a POST request with a content type header set to application/ json. The REST API returns 201 Created
along with the JSON for the new country you added. Here, add_country()
doesn’t contain any validation to confirm that the JSON in the request matches the format of the countries.
01:59
Check out flask-expects-json
if you’d like to validate the format of JSON in Flask. You can use curl
to send a GET request to countries
to confirm that the new country was added.
02:12
If you don’t use the -X
option in your curl
command, then it sends a GET request by default.
02:24 This returns the full list of countries in the system with the newest country at the bottom. Note that if you refresh or revisit the URL in a browser, you get the same result.
02:35 The newest country has been added at the bottom.
02:40 This is just a sample of what Flask can do. The application could be expanded to include endpoints for all the other HTTP methods. Flask has a large ecosystem of extensions that provide additional functionality for REST APIs such as database integrations, authentication, and background processing.
02:59 So having had a look at Flask for API creation, in the next section of the course, you’ll take a look at another option, Django REST Framework.
Become a Member to join the conversation.