In this article, we will learn about how Python API is used to retrieve data from various sources. Also, we will cover all concepts related to Python API from basic to advanced. Various websites provide weather data, Twitter provides data for research purposes, and stock market websites provide data for share prices.
What is an API?
API stands for "Application Programming Interface." In simple terms, it's a set of rules and protocols that allow how different software applications can communicate and interact with each other. APIs define the methods and data formats that applications can use to request and exchange information. To retrieve data from a web server, a client application initiates a request, and the server responds with the requested data.
APIs act as bridges that enable the smooth exchange of data and functionality, enhancing interoperability across various applications.
Prerequisites: Python, API
Making API Requests in Python
In order to work with API some tools are required such as requests so we need to first install them in our system.
Command to install 'requests':
pip install requests
Once we have installed it, we need to import it in our code to use it.
Command to import 'requests':
import requests
Let us understand the working of API with examples. First let us take a simple example.
Example 1: Fetching Live Stock Price Using Alpha Vantage API
This example retrieves the latest opening price for IBM stock at a 5-minute interval. Here we make use of 'requests' to make a call and it is checked with the help of status code that whether our request was successful or not.Then the response is converted to python dictionary and the respected data is stored .
Python
import requests
def get_stock_data():
url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&outputsize=full&apikey=demo"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
last_refreshed = data["Meta Data"]["3. Last Refreshed"]
price = data["Time Series (5min)"][last_refreshed]["1. open"]
return price
else:
return None
price = get_stock_data()
symbol = "IBM"
if price is not None:
print(f"{symbol}: {price}")
else:
print("Failed to retrieve data.")
Output:
APIExplanation:
- Sends a GET request to Alpha Vantage API.
- Checks if the request was successful (status_code == 200).
- Parses JSON response to extract latest opening stock price.
- Prints the price or error message.
Understanding API Status Codes
Status codes tell us how the server handled our request:
- 200 OK: Request successful, data returned.
- 201 Created: New resource created.
- 204 No Content: Success but no data returned.
- 400 Bad Request: Invalid request.
- 401 Unauthorized: Missing or invalid API key.
- 500 Internal Server Error: Server encountered an error.
These codes help in debugging and managing API responses.
Example 2: Fetching News Headlines Using NewsAPI
To fetch news, you often need an API key for authentication. Here’s how to get top business headlines from the US.
Python
import requests
API_KEY = 'your_api_key_here'
url = f"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={API_KEY}"
response = requests.get(url)
print(response.status_code)
Explanation:
- Builds a URL with parameters including API key.
- Sends GET request to NewsAPI.
- Prints status code to confirm request success (200 means OK).
Working with JSON Data
When working with APIs, understanding JSON is key because it’s the common format APIs use to send data. Think of JSON as the language APIs speak to share information like news headlines, images, and descriptions.
To handle this data, we use Python and the requests library to fetch news from NewsAPI. Then, Python helps organize and display the top articles clearly- like a helpful librarian sorting through lots of information for us. This shows how JSON and Python work together to make API data easy to use.
Note: For the below code to run, you need to get you own API credentials.
Python
import json
import requests
def fetch_and_print_articles(api_url):
response = requests.get(api_url)
if response.status_code == 200:
articles = response.json().get('articles', [])
for index, article in enumerate(articles[:1], start=1):
print(f"Article {index}:\n{json.dumps(article, sort_keys=True, indent=4)}\n")
else:
print(f"Error: {response.status_code}")
API_KEY = 'paste_your_api_key_here'
api_endpoint = f"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey={API_KEY}"
fetch_and_print_articles(api_endpoint)
def jprint(obj):
print(json.dumps(obj, sort_keys=True, indent=4))
Output:
Article 1:
{
"author": "SamMobile, Asif Iqbal Shaik",
"content": "As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. The USA banned US-based chipmakers from exporting advanced chips and chip m\u2026 [+2001 chars]",
"description": "As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. ...",
"publishedAt": "2023-12-18T09:07:00Z",
"source": {
"id": null,
"name": "SamMobile"
},
"title": "China bans Apple and Samsung phones from government offices and firms - SamMobile - Samsung news",
"url": "https://www.sammobile.com/news/china-bans-apple-iphone-samsung-phones-government-offices-firms/",
"urlToImage": "https://www.sammobile.com/wp-content/uploads/2023/08/Samsung-Galaxy-Z-Flip-5-Fold-5-China-720x405.jpg"
}
Explanation:
- Parses JSON from the API response.
- enumerate(articles[:1], start=1) prints details of top 1 news article formatted neatly.
- Handles errors by checking response status.
To learn about JSON format in detail refer to: JSON
Using Query Parameters in API Requests
When using an API like NewsAPI, it’s important to specify exactly what data you want. In this example, we fetch the top headlines for the United States. We use the API’s URL (API_URL) and provide our unique API key (API_KEY) for access.
But having just the URL and key isn’t enough. APIs let you customize your request with parameters. Here, we use a params dictionary to set the country to "us" and include our API key to authenticate the request.
Python
import requests
API_URL = "https://newsapi.org/v2/top-headlines"
API_KEY = "your_api_key_here"
params = {
"country": "us",
"apiKey": API_KEY,
"pageSize": 1
}
response = requests.get(API_URL, params=params)
if response.status_code == 200:
print(response.json())
else:
print(f"Error: {response.status_code}")
Output
{
"status": "ok",
"totalResults": 37,
"articles": [
{
"source": {
"id": null,
"name": "BBC News"
},
"author": null,
"title": "Iceland volcano erupts on Reykjanes peninsula - BBC.com",
"description": "The eruption, in south-west Iceland, led to half the sky being \"lit up in red\", an eyewitness says.",
"url": "https://www.bbc.com/news/world-europe-67756413",
"urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/13806/production/_132087897_helicopterstill.jpg",
"publishedAt": "2023-12-19T08:24:57Z",
"content": "By Marita Moloney & Oliver SlowBBC News\r\nSpectacular helicopter shots show the eruption on the island's coast\r\nA volcano has erupted on the Reykjanes peninsula of south-west Iceland after weeks o… [+5343 chars]"
}
]
}
Explanation:
- Defines parameters as a dictionary.
- Passes parameters in the requests.get() call.
- Prints JSON response or error status.
- "pageSize": 1 in params{...} ensure that only 1 headline get fetched (you can modify it accordingly)
Example 3: Tracking the International Space Station (ISS) Location
This example uses several libraries to track ISS in real-time and map its position using Python’s turtle graphics.
Key libraries used:
- json: For decoding JSON data from API.
- turtle: For graphical map display.
- urllib.request: To fetch API data.
- time: For periodic updates.
- webbrowser: To open files.
- geocoder: To find current user location.
Step 1: Fetch Current Astronauts Data
So now there is a problem with tracking ISS because it travels at a speed of almost 28000km/h. Thus, it takes only 90 minutes to complete 1 rotation around the earth. At such a speed, it becomes quite difficult to lock the exact coordinates. So here comes the API to solve this issue. API acts as an intermediate between the website and the program, thus providing the current time data for the program.
In our case, API will provide us with the current location of ISS in earth’s orbit, so visit the link below as an API link for astronaut info.
url = "http://api.open-notify.org/astros.json"
Accessing Data
Use urllib.request.urlopen() function inorder to open the API url and json.loads(.read()) function to read the data from the URL.
Python
import json
import urllib.request
url = "http://api.open-notify.org/astros.json"
response = urllib.request.urlopen(url)
result = json.loads(response.read())
print(result)
Output:
{"number": 10, "people": [{"craft": "ISS", "name": "Sergey Prokopyev"},
{"craft": "ISS", "name": "Dmitry Petelin"},
{"craft": "ISS", "name": "Frank Rubio"},
{"craft": "Tiangong", "name": "Jing Haiping"},
{"craft": "Tiangong", "name": "Gui Haichow"},
{"craft": "Tiangong", "name": "Zhu Yangzhu"},
{"craft": "ISS", "name": "Jasmin Moghbeli"},
{"craft": "ISS", "name": "Andreas Mogensen"},
{"craft": "ISS", "name": "Satoshi Furukawa"},
{"craft": "ISS", "name": "Konstantin Borisov"}], "message": "success"}
Explanation:
- Opens API URL and reads JSON data.
- Prints astronauts currently in space.
Opens API URL and reads JSON data.
Step 2: Save Astronauts Info to File
Create iss.text file using an open() function in write mode and write the result(names & numbers of astronauts) as data inside the file.
Python
file = open("iss.txt", "w")
file.write(f"There are currently {result['number']} astronauts on the ISS:\n\n")
for person in result["people"]:
file.write(person['name'] + " - onboard\n")
file.close()
Step 3: Get User's Current Location
Use geocoder.ip(‘me’) to know your current location in terms of latitude and longitude.
Python
import geocoder
g = geocoder.ip('me')
print(f"Your current location: {g.latlng}")
Step 4: Setup ISS Tracking Map (with Turtle)
Use turtle.screen() function to get access to the screen, then use screen.setup() to set the size and position of the output window. Use screen.setworldcoordinates() function to set the coordinates of all 4 corners on x, y-axis so that when iss reach out from reaches they appear again from another edge.
Python
import turtle
screen = turtle.Screen()
screen.setup(1280, 720)
screen.setworldcoordinates(-180, -90, 180, 90)
screen.bgpic("images/map.gif")
screen.register_shape("images/iss.gif")
iss = turtle.Turtle()
iss.shape("images/iss.gif")
iss.setheading(45)
iss.penup()
Explanation:
- Sets up a map window.
- Loads world map and ISS icon.
- Prepares for ISS position plotting.
Access the current status of ISS using the API below:
url = "http://api.open-notify.org/iss-now.json"
Step 5: Real-time ISS Location Update Loop
Extract the current location of ISS in terms of latitude and longitude from the above API. This script below runs inside the while loop so you can see the updated position and movement of the ISS until you stop the program.
Python
import time
import urllib.request
while True:
url = "http://api.open-notify.org/iss-now.json"
response = urllib.request.urlopen(url)
result = json.loads(response.read())
lat = float(result["iss_position"]["latitude"])
lon = float(result["iss_position"]["longitude"])
print(f"Latitude: {lat}, Longitude: {lon}")
iss.goto(lon, lat)
time.sleep(5)
Explanation:
- Fetches ISS position every 5 seconds.
- Prints coordinates and updates position on map.
Below is the complete code implementation:
Python
import json
import turtle
import urllib.request
import time
import webbrowser
import geocoder
# Fetch current astronauts data from the API
astronauts_url = "http://api.open-notify.org/astros.json"
with urllib.request.urlopen(astronauts_url) as response:
astronauts_data = json.loads(response.read())
# Write astronauts info to a text file
with open("iss.txt", "w") as file:
file.write(f"There are currently {astronauts_data['number']} astronauts on the ISS:\n\n")
for person in astronauts_data["people"]:
file.write(f"{person['name']} - onboard\n")
# Get user's current latitude and longitude
user_location = geocoder.ip('me')
file.write(f"\nYour current lat / long is: {user_location.latlng}")
# Open the text file in the default web browser
webbrowser.open("iss.txt")
# Setup the turtle screen for ISS tracking map
screen = turtle.Screen()
screen.setup(width=1280, height=720)
screen.setworldcoordinates(-180, -90, 180, 90)
# Load world map and ISS icon
screen.bgpic("images/map.gif")
screen.register_shape("images/iss.gif")
# Create the turtle representing the ISS
iss = turtle.Turtle()
iss.shape("images/iss.gif")
iss.setheading(45)
iss.penup()
# API endpoint to get ISS current position
iss_position_url = "http://api.open-notify.org/iss-now.json"
try:
while True:
with urllib.request.urlopen(iss_position_url) as response:
data = json.loads(response.read())
lat = float(data["iss_position"]["latitude"])
lon = float(data["iss_position"]["longitude"])
print(f"Latitude: {lat}")
print(f"Longitude: {lon}")
# Update ISS position on map
iss.goto(lon, lat)
# Pause for 5 seconds before updating again
time.sleep(5)
except KeyboardInterrupt:
print("\nISS tracking stopped by user.")
turtle.bye() # Close turtle window cleanly
Output:
Crew Information: Here is info on the onboarded crew members along with their names.
APIISS Location: Here is a screenshot of the moving ISS i.e orbiting around the earth. You can see it by zooming in on the screenshot.
APIISS Moving look: Here you can see the ISS moving every 5 seconds.
APIWhy Use APIs Instead of Static Data Files?
- Real-time Updates: APIs provide live, constantly updated data (e.g., weather, stock prices).
- Data Size Efficiency: APIs allow fetching only relevant data, unlike downloading large CSV files.
- Specificity: APIs enable targeted queries, minimizing unnecessary data transfer.
Similar Reads
Getting started with Python for Automated Trading Automated Trading is the terminology given to trade entries and exits that are processed and executed via a computer. Automated trading has certain advantages: Minimizes human intervention: Automated trading systems eliminate emotions during trading. Traders usually have an easier time sticking to t
3 min read
Learn Data Science Tutorial With Python Data Science has become one of the fastest-growing fields in recent years, helping organizations to make informed decisions, solve problems and understand human behavior. As the volume of data grows so does the demand for skilled data scientists. The most common languages used for data science are P
3 min read
Getting Started with Pytest Python Pytest is a framework based on Python. It is mainly used to write API test cases. It helps you write better programs. In the present days of REST services, Pytest is mainly used for API testing even though we can use Pytest to write simple to complex test cases, i.e., we can write codes to te
5 min read
Getting Started with Python Programming Python is a versatile, interpreted programming language celebrated for its simplicity and readability. This guide will walk us through installing Python, running first program and exploring interactive codingâall essential steps for beginners.Install PythonBefore starting this Python course first, y
3 min read
Automating Tasks with Python: Tips and Tricks Python is a versatile and simple-to-learn programming language for all developers to implement any operations. It is an effective tool for automating monotonous operations while processing any environment. Programming's most fruitful use is an automation system to identify any process, and Python's
6 min read
Python Automation Tutorial: Beginner to Advanced Python is a very powerful programming language and it's expanding quickly because of its ease of use and straightforward syntax. In this Python Automation Tutorial, we will explore various techniques and libraries in Python to automate repetitive tasks. Automation can save you time and reduce errors
10 min read
Implement a Python REST API with Flask & Flasgger Building a RESTful API in Python can be straightforward with Flask, a lightweight and flexible web framework. To add comprehensive documentation and interactive features to the API, Flasgger is a powerful tool that integrates Swagger UI with Flask. This article guides you through the process of impl
4 min read
Best Way To Start Learning Python - A Complete Roadmap Python...The world's fastest-growing and most popular programming language not just amongst software engineers but also among mathematicians, data analysts, scientists, accountants, network engineers, and even kids! because it's a very beginner-friendly programming language. People from different di
9 min read
Building RESTful APIs with FastAPI FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. There is Another famous framework for doing the same is Flask, which is also Python-based. In this article, we will focus on creating a RESTful API using FastAPI. In this article, we will learn how to create
5 min read
Top 10 Python Applications in Real World We are living in a digital world that is completely driven by chunks of code. Every industry depends on software for its proper functioning be it healthcare, military, banking, research, and the list goes on. We have a huge list of programming languages that facilitate the software development proce
6 min read