Working with APIs in Python

Learn how Python communicates with web services using requests and json.

1️⃣ What is an API?

API (Application Programming Interface) allows two software applications to communicate with each other.

Real-life example:

When your weather app shows temperature, it calls a weather API and receives data from a server.

2️⃣ What is a REST API?

Example API URL: https://api.github.com/users/octocat

3️⃣ HTTP Methods

Method Purpose
GETFetch data
POSTSend new data
PUTUpdate data
DELETERemove data

4️⃣ Python requests Library

The requests library is used to send HTTP requests easily.

import requests

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

5️⃣ JSON in Python

JSON (JavaScript Object Notation) is a lightweight data format.

import json

data = '{"name": "Alice", "age": 25}'
parsed = json.loads(data)

print(parsed["name"])
      

6️⃣ API + JSON Example

import requests

url = "https://api.github.com/users/octocat"
response = requests.get(url)

data = response.json()

print("Username:", data["login"])
print("Public Repos:", data["public_repos"])
      

7️⃣ Headers & Parameters

headers = {
  "User-Agent": "Python-App"
}

params = {
  "page": 1
}

requests.get(url, headers=headers, params=params)
      

8️⃣ Error Handling

if response.status_code == 200:
    print("Success")
else:
    print("Error:", response.status_code)
      

9️⃣ Real Use Cases

🔗 External References