Headers and status codes

Introduction to APIs in Python

Chris Ramakers

Engineering Manager

Request and response message anatomy

An example of a request and response message. Request: GET /users/42 with headers. Response: 200 OK with JSON body containing user info.

Introduction to APIs in Python

The start-line

Example of three distinct parts of a request or response message, with the start line highlighted

  • A server will always include a numeric status code in the response message
Introduction to APIs in Python

Status codes

Status code categories

  • 1XX: Informational responses
  • 2XX: Successful responses
  • 3XX: Redirection messages
  • 4XX: Client error responses
  • 5XX: Server error responses

Frequently used status codes

  • 200: OK
  • 404: Not Found
  • 500: Internal Server Error
1 For a full list of all response codes you can refer to the MDN page on status-codes via https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Introduction to APIs in Python

Headers

Example of three distinct parts of a request or response message, with the headers highlighted

key1: Value 1
key2: Value 2
Introduction to APIs in Python

Example: Content negotiation with headers

Example of three distinct parts of a request or response message, with the headers highlighted

  • Client adds an accept: application/json header to the request
  • Server responds with a content-type: application/json header
Introduction to APIs in Python

Headers with requests

# Adding headers to a request
response = requests.get(
  'https://api.datacamp.com', 
  headers={'accept':'application/json'}
)
# Reading response headers
response.headers['content-type']
'application/json'
response.headers.get('content-type')
'application/json'
Introduction to APIs in Python

Status codes with requests

# Accessing the status code
response = requests.get('https://api.datacamp.com/users/12')

response.status_code == 200
True
# Looking up status codes using requests.codes
response = requests.get('https://api.datacamp.com/this/is/the/wrong/path')

response.status_code == requests.codes.not_found
True
Introduction to APIs in Python

Let's practice!

Introduction to APIs in Python

Preparing Video For Download...