Mit strukturierten Daten arbeiten

Einführung in APIs mit Python

Chris Ramakers

Engineering manager

Komplexe Datenstrukturen

Lyric-API-Antwort

Lyric-API-Antwort mit HTTP 200 OK. Header: Content-Type: plain/text, Content-Language: en-US, Last-Modified: Wed, 21 Oct 2023. Body: Liedtext aus "Problem Child" von AC/DC.

Album-API-Antwort

Album-API-Antwort mit HTTP 200 OK. Header geben JSON-Inhalt an. Der Body enthält Alben-Details zu "Back in Black" von AC/DC mit Trackliste.

Einführung in APIs mit Python

Komplexe Datenstrukturen: JSON

  • JSON
    • JavaScript Object Notation
    • Weit verbreitet
    • Für Menschen lesbar, für Maschinen nutzbar
  • Content-Type, MIME-Type oder Media-Type
  • Andere Formate
    • XML
    • CSV
    • YAML

Album-API-Antwort

Album-API-Antwort mit HTTP 200 OK. Header geben JSON-Inhalt an. Der Body enthält Alben-Details zu "Back in Black" von AC/DC mit Trackliste.

Einführung in APIs mit Python

Von Python zu JSON und zurück

  Grafik zum Kodieren und Dekodieren von JSON-Text mit Python. Das JSON enthält Alben-Details zu "Back in Black" von 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
Einführung in APIs mit Python

JSON-Daten anfordern

# 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
Einführung in APIs mit Python

JSON-Daten senden

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
Einführung in APIs mit Python

Lass uns üben!

Einführung in APIs mit Python

Preparing Video For Download...