Sammanfattning

Introduktion till API:er i Python

Chris Ramakers

Engineering Manager

API-grunder

  • API:ers roll
  • Olika typer av API:er
  • URL-komponenter
  • Uppbyggnad av förfrågnings- och svarsmeddelanden
  • HTTP-verb

Introduktion till API:er i Python

API:er med Python

Requests-paketet

import requests

HTTP-metoder

# Read a resource
requests.get('https://api.my-music.com')
# Create a resource
requests.post('https://api.my-music.com', data={...})
# Update a resource
requests.put('https://api.my-music.com', data={...})
# Delete a resource
requests.delete('https://api.my-music.com')

URL-parametrar

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'))

Statuskoder

response = requests.get('http://api.my-music.com')
print(response.status_code)
Introduktion till API:er i Python

Avancerade ämnen

  • Autentisering
    • Basic Authentication
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API-nyckel/token-autentisering
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • Strukturerad data
    • Begära JSON-formaterad data
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • Skicka JSON-formaterad data
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Introduktion till API:er i Python

Felhantering

  • Typer av fel
    • Anslutningsfel
    • HTTP-fel
      • 4XX Klientfel
      • 5XX Serverfel
  • Hantera fel med statuskoder
    • response.status_code
  • Hantera fel med undantag
    • 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}')
Introduktion till API:er i Python

Grattis!

Introduktion till API:er i Python

Preparing Video For Download...