Python APIs: Making HTTP Requests for Beginners
๐ Quick Info Topic: Making HTTP requests in Python Target Audience: Beginners who know functions and JSON Goal: Understand how to fetch data from the internet with Python 1. Introduction "Every app I used was pulling data from somewhere. Weather apps, social media, online stores โ they all talk to servers. Then I learned about APIs and HTTP requests, and I could finally build programs that talkโฆ
Making HTTP requests in Python allows apps to fetch data from the internet, similar to how weather apps, social media, and online stores communicate with servers. An API (Application Programming Interface) enables two programs to communicate, much like a waiter bringing information from a kitchen.
Without APIs, manually fetching data like weather would require opening a browser, navigating to a site, reading the temperature, and copying it down repeatedly. This process is not scalable or automatable. APIs enable direct communication, making the process efficient and automated.
Using the Python `requests` library, you can fetch data from an API. For example, the following code retrieves live data from GitHub's API:
```python
import requests
response = requests.get("https://api.github.com/users/torvalds")
data = response.json()
print(data["name"])
print(data["public_repos"])
```
This code outputs Linus Torvalds and 100, fetching live data from GitHub.
The code works as follows:
1. `import requests` loads the necessary library.
2. `requests.get(url)` sends an HTTP GET request to the specified URL.
3. `.json()` converts the response to a Python dictionary.
4. `data[ "name" ]` accesses a specific field in the dictionary.
The server responds with HTTP status codes, indicating the success or failure of the request. Common status codes include 200 OK for success, 404 Not Found when the URL doesn't exist, 403 Forbidden when access is denied, and 500 Server Error when the server breaks. Always check the status code to handle errors appropriately.
Here is a real example using a weather API:
```python
import requests
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": 24.86,
"longitude": 67.01,
"current_weather": True
}
response = requests.get(url, params=params)
data = response.json()
print(f"Temperature: {data['current_weather']['temperature']}ยฐC")
```
This example retrieves the temperature in degrees Celsius from the Open-Meteo weather API.
Common mistakes beginners make include not installing the `requests` library, forgetting to use `.json()` to extract data, not handling errors, and hardcoding API keys directly in the code. To avoid these issues, install the library with `pip install requests`, always use `.json()` to access the data, handle errors by checking the status code, and store API keys in environment variables instead of the code.
Written by urgent.news from Dev.to's reporting โ not their text. Machine-written โ may contain errors; check the original before relying on it.