Working with APIs in Python – Fetching & Handling Data Using requests
Working with APIs in Python – Fetching & Handling Data Using requests
If you are learning Python and want to build real-world applications, understanding APIs is very important.
Almost every modern application — from weather apps to payment gateways — uses APIs.
In this blog, you’ll learn:
-
What an API is
-
What the
requestslibrary does -
How to fetch data from an API
-
How to handle JSON responses
-
How to handle errors properly
-
A real example project
What is an API?
API stands for Application Programming Interface.It allows two applications to communicate with each other.
For example:
-
A weather app gets data from a weather API
-
A payment app connects to a bank’s API
-
A website fetches data from a backend server
When you work as a Python developer (especially in web development with frameworks like Django or Flask), APIs are everywhere.
What is the requests Library?
requests is a popular Python library used to:
-
Send HTTP requests
-
Fetch data from APIs
-
Send data to servers
-
Handle responses easily
It is simple and beginner-friendly.
Install requests
pip install requests
Making Your First API Request
Let’s fetch sample data from a free API.
We’ll use:
https://jsonplaceholder.typicode.com/posts
import requests
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
print(response.status_code)
print(response.text)
Output:
200→ Successresponse.text→ Raw data from the API
Understanding JSON Data
Most APIs return data in JSON format.Instead of using response.text, we use:
data = response.json()
print(data[0])
Now the response becomes a Python list or dictionary.
Example output:
{
'userId': 1,
'id': 1,
'title': '...',
'body': '...'
}
Now you can access values like:
print(data[0]['title'])
Handling Errors Properly
Good developers always handle errors.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
print("First title:", data[0]['title'])
except requests.exceptions.HTTPError as err:
print("HTTP Error:", err)
except requests.exceptions.ConnectionError:
print("Connection Error")
except requests.exceptions.Timeout:
print("Timeout Error")
except requests.exceptions.RequestException:
print("Something went wrong")
This makes your application safe and professional.
Sending Data to an API (POST Request)
You can also send data.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
payload = {
"title": "My Post",
"body": "This is my content",
"userId": 1
}
response = requests.post(url, json=payload)
print(response.status_code)
print(response.json())
Common HTTP Methods:
-
GET → Fetch data
-
POST → Create data
-
PUT → Update data
-
DELETE → Remove data
Real-World Example – Weather App
You can build:
-
Weather checker
-
Crypto price tracker
-
News headline app
-
Movie search app
-
Job listing fetcher
All of these use APIs.
Working with API Keys
Many APIs require an API key for authentication.
Example:
url = "https://api.example.com/data?apikey=YOUR_API_KEY"
Never share your API key publicly.
Best Practices
✔ Always check status_code
✔ Use try-except
✔ Keep API keys secret
✔ Use .json() instead of .text
✔ Read API documentation carefully
Why Learning APIs is Important for Your Career
If you want to become:
-
Python Developer
-
Backend Developer
-
Data Analyst
-
Automation Engineer
APIs are a must-know skill.Companies expect developers to:
-
Integrate third-party services
-
Build REST APIs
-
Handle JSON data
Working with APIs using requests is simple and powerful.
Once you master this:
-
You can build real-world applications
-
You can connect your projects to live data
-
You become industry-ready
Comments
Post a Comment