- What is an API? How do we use one?
- Postman
- Dictionaries & JSON
- Break
- The
requests
library - Flask and APIs
- Describe the uses of an API
- Write an API request using Postman
- Use Python to access JSON data
- Use the
requests
library to write an API request
I want to ask the user of my website what their favorite color is. How do I do so, and display the answer, in Flask?
- Application Programming Interface
- Used to get data from a web URL
- Just like a normal website! Except instead of serving HTML, it is serving JSON data
- We want to use that data in our web app
- REST = Representational State Transfer
- A REST API has endpoints that allow us to do operations on objects
Aka, CRUD (Create, Read, Update, Delete) operations
-
GET
/dogs?breed=shiba+inu
- show me all shiba inu dogs (Read) -
GET
/dogs/1
- show me the dog with id 1 (Read) -
POST
/dogs
- enter a new dog into the database (Create) -
PUT/PATCH
/dogs/1
- update the dog with id 1 (Update) -
DELETE
/dogs/1
- delete the dog with id 1 (Delete)
Follow the documentation to get a random Chuck Norris joke!
What if I only want a nerdy joke?
http://api.icndb.com/jokes/random?limitTo=nerdy
Download Postman for Mac here:
https://www.getpostman.com/downloads/
Use Postman to try out the Chuck Norris API! Use the documentation to help you complete the following challenges.
- Make a request for a random joke.
- Make a request for 100 jokes.
- Make a request for the list of joke categories.
A dictionary is a Python data type that stores key-value pairs.
Key | Value |
---|---|
"name" | "Bananas" |
"price" | 0.99 |
"num_in_stock" | 200 |
We can use a dictionary in Python like:
fruit = {
"name": "Bananas",
"price": 0.99,
"num_in_stock": 200
}
We can access a field in our dictionary like:
>>> fruit["name"]
"Bananas"
We can set a new field in our dictionary like:
fruit["color"] = "yellow"
This is exactly like using a list! Except instead of being associated with a numerical index, the values are associated with a string key.
Open up the Python interpreter and type the following:
>>> fruit = {
... "name": "Bananas",
... "price": 0.99
... }
Try setting and accessing at least 2 different fields.
Install the requests
library:
$ pip3 install requests
Use the requests.get
function to send a GET request to your API.
This function returns a Response
Object. We need to call .json()
to get the JSON data.
>>> import requests
>>> r = requests.get("http://api.icndb.com/jokes/random?limitTo=nerdy")
>>> joke_json = r.json()
Remember that our JSON data looks like this:
{ "type": "success", "value": {
"id": 505,
"joke": "Chuck Norris can spawn threads that complete before they are started.",
"categories": ["nerdy"] }
}
Once we have a JSON object, we can extract the fields we want using bracket notation:
>>> joke_str = joke_json["value"]["joke"]
>>> joke_str
"Chuck Norris can spawn threads that complete before they are started."
The part of the URL after the ?
is the query string.
http://api.icndb.com/jokes/random?limitTo=nerdy
If our URL has a lot of query parameters, it can get a little messy.
http://fakeapi.com/search?term=wow+very+long&filter=much+long+wow&name=whoa+cool+person
We can use requests
to set the query string for us:
my_params = {
"term": "wow very long",
"filter": "much long wow",
"name": "whoa cool person"
}
r = requests.get("http://fakeapi.com/search", params=my_params)
import requests
from pprint import PrettyPrinter
pp = PrettyPrinter(indent=4)
params = { "limitTo": "nerdy" }
r = requests.get("http://api.icndb.com/jokes/random", params=params)
joke_json = r.json()
pp.pprint(joke_json)
import requests
from flask import Flask
app = Flask(__name__)
@app.route('/joke')
def make_joke():
params = { "limitTo": "nerdy" }
r = requests.get("http://api.icndb.com/jokes/random", params=params)
joke_json = r.json()
joke_str = joke_json["value"]["joke"]
return joke_str
Let's try running it!
$ export FLASK_ENV=development
$ flask run
Modify the code in our joke route to:
- Show a joke for "Ada Lovelace" instead of "Chuck Norris"
- Ask the user their name, and tell them a joke about themselves