Python Docs

Working with APIs

Python makes it simple to communicate with web APIs using the requests library. You can easily make GET/POST requests, send data, handle JSON responses, and implement basic error handling.

Quick Example

A basic GET request using the GitHub public API:

import requests

resp = requests.get('https://api.github.com')

print(resp.status_code)   # Response code
print(resp.json())        # Parsed JSON

POST Request

Sending data with a POST request:

import requests

payload = {
    "name": "Lal Bahadur",
    "role": "Developer"
}

resp = requests.post("https://httpbin.org/post", json=payload)
print(resp.json())

Basic Error Handling

Always check for network errors or non-200 responses.

import requests

try:
    resp = requests.get("https://api.github.com/invalid-url")
    resp.raise_for_status()   # Raise exception for bad status
except requests.exceptions.RequestException as e:
    print("Error:", e)

Headers

Sending custom headers (e.g., API keys):

headers = {
    "Authorization": "Bearer YOUR_TOKEN_HERE"
}

resp = requests.get("https://api.github.com/user", headers=headers)
print(resp.json())