Laatste gedachten

Introductie tot API's in Python

Chris Ramakers

Engineering Manager

API-basis

  • De rol van API's
  • Typen API's
  • URL-onderdelen
  • Opbouw van request- en response-berichten
  • HTTP-verbs

Introductie tot API's in Python

API's met Python

Requests-pakket

import requests

HTTP-methoden

# Lees een resource
requests.get('https://api.my-music.com')
# Maak een resource
requests.post('https://api.my-music.com', data={...})
# Werk een resource bij
requests.put('https://api.my-music.com', data={...})
# Verwijder een resource
requests.delete('https://api.my-music.com')

URL-parameters

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

Headers

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)
Introductie tot API's in Python

Geavanceerde onderwerpen

  • Authenticatie
    • Basic authentication
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API-sleutel/token-authenticatie
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • Gestructureerde data
    • JSON-data opvragen
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • JSON-data versturen
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Introductie tot API's in Python

Foutafhandeling

  • Soorten fouten
    • Verbindingsfouten
    • HTTP-fouten
      • 4XX Clientfouten
      • 5XX Serverfouten
  • Fouten afhandelen met statuscodes
    • response.status_code
  • Fouten afhandelen met exceptions
    • 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}')
Introductie tot API's in Python

Gefeliciteerd!

Introductie tot API's in Python

Preparing Video For Download...