Python API Requests Tutorial – Using the requests Library

⏱︎

Read time:

1–2 minutes
python-api

Introduction

The Python requests library is the most popular way to make HTTP requests. Whether you’re consuming REST APIs, scraping web data, or integrating with third-party services, requests makes it simple and intuitive. This tutorial covers everything from basic GET requests to advanced authentication.

Installing the requests Library

pip install requests

Making a GET Request

import requests

response = requests.get(‘https://jsonplaceholder.typicode.com/posts/1’)

print(response.status_code)  # 200

print(response.json())  # {‘userId’: 1, ‘id’: 1, ‘title’: ‘…’}

Making a POST Request

import requests

data = {‘title’: ‘My Post’, ‘body’: ‘Content here’, ‘userId’: 1}

response = requests.post(

    ‘https://jsonplaceholder.typicode.com/posts’,

    json=data

)

print(response.status_code)  # 201

print(response.json())

Adding Headers and Authentication

headers = {

    ‘Authorization’: ‘Bearer YOUR_TOKEN’,

    ‘Content-Type’: ‘application/json’

}

response = requests.get(‘https://api.example.com/data’, headers=headers)

print(response.json())

Error Handling

try:

    response = requests.get(‘https://api.example.com/data’, timeout=5)

    response.raise_for_status()  # Raises exception for 4xx/5xx

    print(response.json())

except requests.exceptions.HTTPError as e:

    print(f’HTTP Error: {e}’)

except requests.exceptions.ConnectionError:

    print(‘Connection failed’)

except requests.exceptions.Timeout:

    print(‘Request timed out’)

Conclusion

This guide covered “Python API Requests Tutorial – Using the requests Library”. Bookmark this page and keep it as your go-to reference. If you found this helpful, share it with fellow developers and check out more snippets on programsnippet.com!

Leave a Reply

Your email address will not be published. Required fields are marked *