🐍 Python Tutorial: Working with APIs

APIs (Application Programming Interfaces) allow Python programs to interact with web services. Common use cases include retrieving weather data, stock prices, or sending data to cloud services. This tutorial covers how to consume APIs using the requests library.


1. Getting Started with requests

The requests library makes HTTP requests easy. You can send GET, POST, PUT, DELETE, and other types of requests to interact with APIs.

import requests

response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())

2. Passing Parameters

APIs often require query parameters. These can be passed using the params argument:

params = {'q': 'python', 'sort': 'stars'}
url = "https://api.github.com/search/repositories"
response = requests.get(url, params=params)
print(response.json())

3. Sending Data with POST

When sending data to an API (e.g., submitting a form), use the POST method and pass data using the json or data keyword.

url = "https://httpbin.org/post"
data = {"name": "Alice", "email": "alice@example.com"}
response = requests.post(url, json=data)
print(response.json())

4. Headers and Authentication

Some APIs require authentication via API keys or tokens. These are usually passed in the headers:

headers = {"Authorization": "Bearer YOUR_TOKEN"}
url = "https://api.example.com/data"
response = requests.get(url, headers=headers)
print(response.status_code)

Additional Resources & References


← Back : AutomationNext: Web Scraping →