Learn how Python communicates with web services using requests
and json.
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.
Example API URL:
https://api.github.com/users/octocat
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Send new data |
| PUT | Update data |
| DELETE | Remove data |
requests LibraryThe 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)
JSON (JavaScript Object Notation) is a lightweight data format.
import json
data = '{"name": "Alice", "age": 25}'
parsed = json.loads(data)
print(parsed["name"])
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"])
headers = {
"User-Agent": "Python-App"
}
params = {
"page": 1
}
requests.get(url, headers=headers, params=params)
if response.status_code == 200:
print("Success")
else:
print("Error:", response.status_code)