Skip to content

Making a GET Request

import requests 

# The API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"

# A get request to the API
response = requests.get(url)

# Print the response
response_json = response.json()
print(response_json)
# Print status code from original response (not JSON) 
print(response.status_code)

Passing an argument

# The API endpoint
url = "https://jsonplaceholder.typicode.com/posts/"

# Adding a payload
payload = {"id": [1, 2, 3], "userId":1}

# A get request to the API
response = requests.get(url, params=payload)

# Print the response 
response_json = response.json()

for i in response_json:
    print(i, "\n")
    
# Another way to view response
response.text

Making a POST request

# Define new data to create
new_data = {
    "userId": 1, 
    "id": 1, 
    "title": "Making a POST request",
    "body": "This is the data we created."
}

# The API endpoint to communicate with
url_post = "https://jsonplaceholder.typicode.com/posts/"

# A POST request to tthe API
post_response = requests.post(url_post, json=new_data)

# Print the response
post_response_json = post_response.json()
print(post_response_json)
# Print status code from original response (not JSON) 
print(post_response.status_code)

Advanced Topics

Authenticating requests

"""
Fill in the username and token section with your credentials
then uncomment the code and run this cell. 
"""
# from requests.auth import HTTPBasicAuth

# private_url = "https://api.github.com/user"
# github_username = "username"
# token = "token"

# private_url_response = requests.get(
#     url=private_url,
#     auth=HTTPBasicAuth(github_username, token)
# )

# private_url_response.status_code

Handling Errors

# A deliberate typo is made in the endpoint "postz" instead of "posts"
url = "https://jsonplaceholder.typicode.com/postz"

# Attempt to GET data from provided endpoint
try: 
    response = requests.get(url)
    response.raise_for_status()
# If the request fails (404) then print the error. 
except requests.exceptions.HTTPError as error:
   print(error)

Dealing with too many redirects