The basic anatomy of an API request

Introduction to APIs in Python

Chris Ramakers

Engineering Manager

What are URLs?

  • URL = Uniform Resource Locator
  • The structured address to an API Resource
  • Customize the URL to interact with specific API Resources
http://350.5th-ave.com/unit/243
Introduction to APIs in Python

Dissecting the URL

A diagram showing different parts of a URL: Protocol (http://), Domain (350.5th-ave.com), Port (:80), Path (/unit/243), and Query (?floor=77).

  • Protocol = the means of transportation
  • Domain = the street address of the office building
  • Port = the gate or door to use when entering the building
  • Path = the specific office unit inside the building
  • Query = any additional instructions
Introduction to APIs in Python

Adding query parameters with requests

# Append the query parameter to the URL string
response = requests.get('http://350.5th-ave.com/unit/243?floor=77&elevator=True')
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
  • Use the params argument to add query parameters
# Create dictionary
query_params = {'floor': 77, 'elevator': True}
# Pass the dictionary using the `params` argument
response = requests.get('http://350.5th-ave.com/unit/243', params=query_params)
print(response.url)
http://350.5th-ave.com/unit/243?floor=77&elevator=True
Introduction to APIs in Python

HTTP Verbs

  • Destination: Unit 243 of the 350 5th Ave office building
  • URL: http://350.5th-ave.com/unit/243

Actions

Verb Action Description
GET Read Check the mailbox contents
POST Create Drop a new package in the mailbox
PUT Update Replace all packages with a new one
DELETE Delete Remove all packages from the mailbox
1 There are 9 HTTP verbs in total, but for simple REST APIs only these 4 are relevant
Introduction to APIs in Python

Sending data via POST and PUT

# GET = Retrieve a resource
response = requests.get('http://350.5th-ave.com/unit/243')

# POST = Create a resource response = requests.post('http://350.5th-ave.com/unit/243', data={"key": "value"}) # PUT = Update an existing resource response = requests.put('http://350.5th-ave.com/unit/243', data={"key": "value"})
# DELETE = Remove a resource response = requests.delete('http://350.5th-ave.com/unit/243')
  • Each verb has it's own method in the requests package
  • Use the data argument to pass data to a POST or PUT request.
Introduction to APIs in Python

Let's practice!

Introduction to APIs in Python

Preparing Video For Download...