Skip to content

Latest commit

 

History

History
344 lines (217 loc) · 6.81 KB

File metadata and controls

344 lines (217 loc) · 6.81 KB

URLs, HTTP, REST, and Reading Errors

Agenda

  1. What is an API? How do we use one?
  2. Postman
  3. Dictionaries & JSON
  4. Break
  5. The requests library
  6. Flask and APIs

Learning Outcomes

  1. Describe the uses of an API
  2. Write an API request using Postman
  3. Use Python to access JSON data
  4. Use the requests library to write an API request

Warm Up [15 min]

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?

APIs

APIs

  • 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

What is a REST API?

  • REST = Representational State Transfer
  • A REST API has endpoints that allow us to do operations on objects

What are REST Operations?

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)

Example: Chuck Norris API

Follow the documentation to get a random Chuck Norris joke!

http://www.icndb.com/api/

URL Query Parameters

What if I only want a nerdy joke?

http://api.icndb.com/jokes/random?limitTo=nerdy

Introducing Postman

Download Postman for Mac here:

https://www.getpostman.com/downloads/

Activity [15 mins]

Use Postman to try out the Chuck Norris API! Use the documentation to help you complete the following challenges.

  1. Make a request for a random joke.
  2. Make a request for 100 jokes.
  3. Make a request for the list of joke categories.

Review: Dictionaries

What is a Dictionary?

A dictionary is a Python data type that stores key-value pairs.

Key Value
"name" "Bananas"
"price" 0.99
"num_in_stock" 200

How do we use Dictionaries?

We can use a dictionary in Python like:

fruit = {
    "name": "Bananas",
    "price": 0.99,
    "num_in_stock": 200
}

Accessing a Field

We can access a field in our dictionary like:

>>> fruit["name"]
"Bananas"

Setting a Field

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.

Practice

Open up the Python interpreter and type the following:

>>> fruit = {
...     "name": "Bananas",
...     "price": 0.99
... }

Try setting and accessing at least 2 different fields.

Break [10 minutes]

The requests Library

Install requests

Install the requests library:

$ pip3 install requests

Using 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()

Get the Data

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."

Set the Query String

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

Set the Query String

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)

Flask and APIs

Let's Make a Joke Program

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)

Turn it Into a Flask Route

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

Run the Server

Let's try running it!

$ export FLASK_ENV=development
$ flask run

Activity

Modify the code in our joke route to:

  1. Show a joke for "Ada Lovelace" instead of "Chuck Norris"
  2. Ask the user their name, and tell them a joke about themselves

Resources

  1. Slides
  2. What is HTTP?
  3. Explained HTTP, HTTPS, SSL/TLS
  4. REST Wikipedia Article
  5. REST & HTTP
  6. Intro to REST