G
GuideDevOps
Lesson 7 of 15

Requests & API Calls

Part of the Python for DevOps tutorial series.

DevOps engineers frequently interact with REST APIs, from cloud providers like AWS or GCP to monitoring tools like Datadog or Prometheus. The requests library is the industry standard for HTTP operations.

1. GET Requests

Use requests.get() to fetch data from an API.

Action:

import requests
 
# We'll use a public API as an example
response = requests.get("https://api.github.com/zen")
 
if response.status_code == 200:
    print(f"Status: {response.status_code}")
    print(f"Message: {response.text}")

Result:

Status: 200
Message: Practicality beats purity.

Working with JSON

Most modern APIs return JSON data.

Action:

import requests
 
response = requests.get("https://api.github.com/repos/psf/requests")
data = response.json()
 
print(f"Repo: {data['name']}")
print(f"Stars: {data['stargazers_count']}")

Result:

Repo: requests
Stars: 51234

2. POST Requests

Use requests.post() to send data to an API (e.g., creating a ticket or triggering a build).

Action:

import requests
 
# Example: Sending a dummy message
data = {"title": "Build Failed", "body": "Check pipeline #1234"}
response = requests.post("https://httpbin.org/post", json=data)
 
print(f"Status: {response.status_code}")
# Print part of the JSON response
print(f"Sent Data: {response.json()['json']}")

Result:

Status: 200
Sent Data: {'body': 'Check pipeline #1234', 'title': 'Build Failed'}

3. Headers and Authentication

Many APIs require an API Key or Token in the headers.

Action:

import requests
 
headers = {
    "Authorization": "Bearer my_secret_token",
    "Accept": "application/json"
}
 
# Example of a request with custom headers
response = requests.get("https://httpbin.org/headers", headers=headers)
print(response.json()['headers']['Authorization'])

Result:

Bearer my_secret_token

4. Error Handling

Always use raise_for_status() to catch HTTP errors (4xx or 5xx).

Action:

import requests
 
try:
    # This URL returns a 404 error
    response = requests.get("https://httpbin.org/status/404")
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e}")

Result:

HTTP Error: 404 Client Error: NOT FOUND for url: https://httpbin.org/status/404

Summary

  • Use response.json() to automatically parse JSON.
  • Always check response.status_code or use raise_for_status().
  • Use the json= parameter in post() to automatically set the Content-Type.
  • requests is not built-in; install it with pip install requests.