Final thoughts

Introduction to APIs in Python

Chris Ramakers

Engineering Manager

API basics

  • The role of APIs
  • Different types of APIs
  • URL components
  • Anatomy of request & response messages
  • HTTP Verbs

Introduction to APIs in Python

APIs with Python

Requests package

import requests

HTTP methods

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

Status codes

response = requests.get('http://api.my-music.com')
print(response.status_code)
Introduction to APIs in Python

Advanced topics

  • Authentication
    • Basic Authentication
      headers = {'Authorization':'Basic am9obkBleGF...'}
      
    • API key/token authentication
      headers = {'Authorization': 'Bearer faaa1c9f4...'}
      
  • Structured data
    • Requesting JSON formatted data
      requests.get('https://api.my-music.com', headers={'accept': 'application/json'})
      
    • Sending JSON formatted data
      playlists = [{"Name":"My favorite songs"}, {"Name":"Road Trip"}]
      requests.post('https://api.my-music.com/playlists/', json=playlists)
      
Introduction to APIs in Python

Error handling

  • Types of errors
    • Connection errors
    • HTTP errors
      • 4XX Client errors
      • 5XX Server errors
  • Handling errors with status codes
    • response.status_code
  • Handling errors with 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}')
Introduction to APIs in Python

Congratulations!

Introduction to APIs in Python

Preparing Video For Download...