Abschließende Gedanken

Einführung in APIs mit Python

Chris Ramakers

Engineering Manager

API-Grundlagen

  • Rolle von APIs
  • API-Typen
  • URL-Bausteine
  • Aufbau von Request & Response
  • HTTP-Verben

Einführung in APIs mit Python

APIs mit Python

Requests-Paket

import requests

HTTP-Methoden

# Ressource lesen
requests.get('https://api.my-music.com')
# Ressource erstellen
requests.post('https://api.my-music.com', data={...})
# Ressource aktualisieren
requests.put('https://api.my-music.com', data={...})
# Ressource löschen
requests.delete('https://api.my-music.com')

URL-Parameter

query_params = {'artist': 'Deep Purple'}
requests.get('http://api.my-music.com', params=query_params)

Header

headers = {'accept': 'application/json'}
response = requests.get('http://api.my-music.com', headers=headers)
print(response.headers.get('content-type'))

Statuscodes

response = requests.get('http://api.my-music.com')
print(response.status_code)
Einführung in APIs mit Python

Fortgeschrittene Themen

  • Authentifizierung
    • Basic Authentication
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API-Key/Token-Auth
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • Strukturierte Daten
    • JSON anfordern
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • JSON senden
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Einführung in APIs mit Python

Fehlerbehandlung

  • Fehlertypen
    • Verbindungsfehler
    • HTTP-Fehler
      • 4XX Client-Fehler
      • 5XX Server-Fehler
  • Fehler per Statuscodes behandeln
    • response.status_code
  • Fehler per Exceptions behandeln
    • raise_for_error()
import requests
from requests.exceptions import ConnectionError, HTTPError

try:
    response = requests.get("http://api.music-catalog.com/albums") 
    response.raise_for_status()

except ConnectionError as conn_err: 
    print(f'Connection Error! {conn_err}.')

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
Einführung in APIs mit Python

Glückwunsch!

Einführung in APIs mit Python

Preparing Video For Download...