Python API Tutorial: Getting Started with APIs (original) (raw)

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. Let's learn about how to work with APIs in Python

Making API Requests in Python

In order to work with APIs, some tools are required, such as requests module and 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

This example retrieves the latest opening price for IBM stock at a 5-minute interval from alphavantage api endpoint. Here we are using ****'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:

Python-API-Tutorial_-Getting-Started-with-APIs---Write

API

**Explanation:

Understanding API Status Codes

Status codes tell us how the server handled our request:

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=%7BAPI_KEY%7D" response = requests.get(url) print(response.status_code)

`

**Explanation:

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=%7BAPI_KEY%7D"

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:

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:

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:

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.

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:

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:

**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.

Python-API-Tutorial_-Getting-Started-with-APIs---Write-(1)

API

**ISS 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.

Getting Started with APIs

API

**ISS Moving look: Here you can see the ISS moving every 5 seconds.

Getting Started with APIs in Python

API

Why Use APIs Instead of Static Data Files?