Arbeta med strukturerad data

Introduktion till API:er i Python

Chris Ramakers

Engineering manager

Komplexa datastrukturer

API-svar med låttext

API-svar med låttext, HTTP 200 OK. Headers: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. Body: låttext från "Problem Child" av AC/DC.

API-svar med albuminfo

API-svar med albuminfo, HTTP 200 OK. Headers anger JSON-innehåll. Body innehåller albumdetaljer för "Back in Black" av AC/DC med spårtitlar.

Introduktion till API:er i Python

Komplexa datastrukturer: JSON

  • JSON
    • JavaScript Object Notation
    • Brett stöd
    • Läsbart för både människor och maskiner
  • Content-type, mime-type eller media-type
  • Andra format
    • XML
    • CSV
    • YAML

API-svar med albuminfo

API-svar med albuminfo, HTTP 200 OK. Headers anger JSON-innehåll. Body innehåller albumdetaljer för "Back in Black" av AC/DC med spårtitlar.

Introduktion till API:er i Python

Från Python till JSON och tillbaka

  En visuell representation av kodning och avkodning av JSON-formaterad text med Python. JSON innehåller albumdetaljer för "Back in Black" av AC/DC.

import json
album =  {'id': 42, 'title':"Back in Black"}
string = json.dumps(album) # Encodes a python object to a JSON string
album = json.loads(string) # Decodes a JSON string to a Python object
Introduktion till API:er i Python

Hämta JSON-data

# GET request without headers
response = requests.get('http://api.music-catalog.com/lyrics')
print(response.text)
N' I never miss Cause I'm a problem child - AC/DC, Problem Child
# GET request with an accept header
response = requests.get('http://api.music-catalog.com/lyrics', headers={'accept': 'application/json'})

# Print the JSON text
print(response.text)

# Decode into a Python object data = response.json() print(data['artist'])
{'artist': 'AC/DC', 'lyric': "N' I never miss Cause I'm a problem child", 'track': 'Problem Child'}

AC/DC
Introduktion till API:er i Python

Skicka JSON-data

import requests
playlist = {"name": "Road trip", "genre":"rock", "private":"true"}

# Add the playlist using via the `json` argument 
response = requests.post("http://api.music-catalog.com/playlists", json=playlist)
# Get the request object
request = response.request

# Print the request content-type header
print(request.headers['content-type'])
application/json
Introduktion till API:er i Python

Nu kör vi en övning!

Introduktion till API:er i Python

Preparing Video For Download...