Skip to main content

9.8 - API Practical Examples

This chapter provides in-depth, real-world examples of how to effectively integrate and utilize various popular APIs using Python. By following these detailed code snippets and comprehensive explanations, you'll learn to leverage these APIs for both common and advanced use cases.

Notes:

The source code examples provided in this guide serve as foundational templates designed to help you get started with various APIs. To fully operationalize these scripts in your projects, you will need to:

  1. Insert Your Credentials: Replace placeholders such as YOUR_API_KEY, YOUR_ACCESS_TOKEN, YOUR_CLIENT_ID, and other similar tokens with your actual credentials. These are necessary for authenticating requests to the respective API services.

  2. Customize the Code: Depending on your specific requirements, you may need to modify these scripts. Customization can include altering functionality, optimizing performance, or enhancing security practices. It’s important to review and tailor the code to fit your application’s needs.

  3. User Interface Integration: For applications intended for end-user interaction, consider integrating these scripts with a graphical user interface (GUI). A GUI can provide a more intuitive and accessible way for users to interact with your application, thereby improving user experience.

  4. Testing: Before deploying the code in a production environment, thoroughly test it in a controlled setting. Ensure that it handles edge cases and responds gracefully to unexpected inputs or API downtime.

  5. Security Measures: Always secure your API keys and sensitive data. Avoid hard-coding credentials directly in your source code, especially in environments where code might be exposed (e.g., client-side JavaScript or public repositories). Use environment variables or secure vault solutions to manage sensitive information securely.

  6. Error Handling: Implement robust error handling to manage API limits, connectivity issues, and data exceptions. This practice helps prevent your application from crashing and provides users with a better understanding of what went wrong.

  7. Documentation and Comments: Maintain comprehensive documentation and comments within your code to ensure that it is easily understandable for other developers who may work on your project in the future. This includes describing what each part of the code does, why certain decisions were made, and how different components are interconnected.

By following these guidelines, you can effectively adapt and extend these code examples to build sophisticated and robust applications tailored to your unique use cases.

9.8.1 - Integrating with the Twitter API

Enhance your applications by integrating Twitter functionality using the tweepy library.

9.8.1.1 - Posting a Tweet

Here's how to post a tweet using the Twitter API v2:

import tweepy

# Authentication with Twitter
auth = tweepy.OAuthHandler("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_SECRET")
auth.set_access_token("YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET")
api = tweepy.API(auth)

# Creating and posting a tweet
tweet = api.update_status("Hello, world! This is my first tweet.")
print(f"Posted: {tweet.text}")

9.8.1.2 - Searching for Tweets

Search for tweets containing specific keywords:

import tweepy

# Authentication setup
auth = tweepy.OAuthHandler("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_SECRET")
auth.set_access_token("YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET")
api = tweepy.API(auth)

# Tweet search example
for tweet in api.search(q="Python", lang="en", rpp=10):
print(f"{tweet.user.name}: {tweet.text}")

9.8.1.3 - Streaming Tweets

Monitor tweets in real-time based on keywords:

import tweepy

# Setup authentication
auth = tweepy.OAuthHandler("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_SECRET")
auth.set_access_token("YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET")
api = tweepy.API(auth)

# Define a stream listener
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text)

# Initialize and start the tweet stream
my_stream = tweepy.Stream(auth=api.auth, listener=MyStreamListener())
my_stream.filter(track=['Python'])

9.8.2 - Using the Google Maps API

Utilize Google Maps API for geocoding, directions, and map integration.

9.8.2.1 - Geocoding an Address

Convert an address into geographical coordinates:

import googlemaps

# Google Maps client initialization
gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Address geocoding
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
print(geocode_result[0]['geometry']['location'])

9.8.2.2 - Calculating Directions

Retrieve directions between two points:

import googlemaps
from datetime

import datetime

# Initialize the Google Maps client
gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Get directions
now = datetime.datetime.now()
directions_result = gmaps.directions("Sydney Town Hall",
"Parramatta, NSW",
mode="driving",
departure_time=now)

# Output directions
duration = directions_result[0]['legs'][0]['duration']['text']
distance = directions_result[0]['legs'][0]['distance']['text']
print(f"Driving from Sydney Town Hall to Parramatta takes {duration} and covers {distance}.")

9.8.2.3 - Displaying Maps

Show a map centered on a specific location:

import googlemaps
from IPython.display import display

# Set up Google Maps
gmaps = googlemaps.Client(key='YOUR_API_KEY')

# Generate map
location = gmaps.geocode('Eiffel Tower')
map = gmaps.static_map(center=location[0]['geometry']['location'], zoom=15)
display(map)

9.8.3 - Working with the OpenWeather API

Retrieve weather data and forecasts using the OpenWeather API.

9.8.3.1 - Fetching Current Weather Data

Get current weather conditions for a specified location:

import requests

# API configuration
api_key = "YOUR_API_KEY"
base_url = "http://api.openweathermap.org/data/2.5/weather?"

# Define city
city_name = "London"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# Request weather data
response = requests.get(complete_url)
data = response.json()

# Display weather information
if data["cod"] != "404":
main = data["main"]
temperature = main["temp"]
humidity = main["humidity"]
weather_description = data["weather"][0]["description"]
print(f"Weather in {city_name}: {weather_description}\nTemperature: {temperature} Kelvin\nHumidity: {humidity}%")
else:
print("City not found!")

9.8.3.2 - Forecasting Weather

Provide a 5-day weather forecast for a specific location:

import requests

# Configure the API
api_key = "YOUR_API_KEY"
base_url = "http://api.openweathermap.org/data/2.5/forecast?"

# Specify the city
city_name = "Tokyo"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# Fetch the forecast
response = requests.get(complete_url)
data = response.json()

# Process and display forecast
if data["cod"] != "404":
for item in data["list"]:
print(f"Date: {item['dt_txt']}, Temperature: {item['main']['temp']} Kelvin, Weather: {item['weather'][0]['description']}")
else:
print("City not found!")

9.8.4 - Interacting with the YouTube API

Use the YouTube API to search for videos and retrieve video details.

9.8.4.1 - Searching for Videos

Search for YouTube videos using keywords:

from googleapiclient.discovery import build

# Initialize the API
youtube = build('youtube', 'v3', developerKey='YOUR_API_KEY')

# Conduct a search
request = youtube.search().list(
part="snippet",
q="Python programming",
type="video",
maxResults=10
)
response = request.execute()

# Print search results
for item in response['items']:
print(f"Title: {item['snippet']['title']}, URL: https://www.youtube.com/watch?v={item['id']['videoId']}")

9.8.4.2 - Retrieving Video Statistics

Get detailed statistics for a specific YouTube video:

from googleapiclient.discovery import build

# Setup the API
youtube = build('youtube', 'v3', developerKey='YOUR_API_KEY')

# Get video details
request = youtube.videos().list(
part="snippet,contentDetails,statistics",
id="dQw4w9WgXcQ" # Replace with the actual video ID
)
response = request.execute()

# Display video statistics
for item in response['items']:
print(f"Title: {item['snippet']['title']}, View Count: {item['statistics']['viewCount']}")

9.8.5 - Leveraging the Spotify API

Explore how to use the Spotify API to manage user playlists, search for music, and retrieve track recommendations.

9.8.5.1 - Searching for Music

Find tracks, artists, and albums using specific search queries:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# Authentication
client_credentials_manager = SpotifyClientCredentials(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# Search for tracks
results = sp.search(q='Beatles', limit=20)
for idx, track in enumerate(results['tracks']['items']):
print(idx, track['name'], '-', track['artists'][0]['name'])

9.8.5.2 - Managing User Playlists

Create and modify user playlists:

import spotipy
from spotipy.oauth2 import SpotifyOAuth

# Authenticate with necessary scope
scope = 'playlist-modify-public'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# Create a new playlist
playlist = sp.user_playlist_create(user='YOUR_USERNAME', name='New Playlist', public=True)
print(f"Created playlist {playlist['name']}")

# Add tracks to the playlist
track_ids = ['TRACK_ID1', 'TRACK_ID2'] # Replace track IDs
sp.user_playlist_add_tracks(user='YOUR_USERNAME', playlist_id=playlist['id'], tracks=track_ids)

9.8.5.3 - Retrieving Track Recommendations

Get music recommendations based on seed artists, genres, and tracks:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# Setup client credentials
client_credentials_manager = SpotifyClientCredentials(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# Get recommendations
recommendations = sp.recommendations(seed_artists=['ARTIST_ID'], seed_genres=['indie'], seed_tracks=['TRACK_ID'])
for track in recommendations['tracks']:
print(track['name'], '-', track['artists'][0]['name'])

9.8.6 - Using the Slack API

Integrate Slack for messaging, automation, and team interactions.

9.8.6.1 - Sending Messages

Send messages to channels or direct messages on Slack:

import slack_sdk

# Initialize the client
client = slack_sdk.WebClient(token='YOUR_SLACK_TOKEN')

# Send a message
response = client.chat_postMessage(channel='#general', text='Hello, world!')
print(f"Message sent: {response['message']['text']}")

9.8.6.2 - Automating Responses

Automate responses to certain messages using event listeners:

from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from flask import Flask, request, Response

app = Flask(__name__)
client = WebClient(token='YOUR_SLACK_TOKEN')

@app.route("/slack/events", methods=["POST"])
def slack_events():
data = request.json
if 'challenge' in data:
return Response(data['challenge'], mimetype='text/plain')
elif 'event' in data:
event = data['event']
if event['type'] == 'message' and 'Hello' in event['text']:
try:
response = client.chat_postMessage(channel=event['channel'], text="Hi there!")
print(f"Automated response sent: {response['message']['text']}")
except SlackApiError as e:
print(f"Error sending message: {e.response['error']}")
return Response(), 200

if __name__ == "__main__":
app.run(port=3000)

9.8.7 - Interacting with the GitHub API

Use the GitHub API to automate repository management, issue tracking, and fetching user information.

9.8.7.1 - Creating Repositories

Automatically create new repositories on GitHub:

from github import Github

# Initialize using token
g = Github("YOUR_ACCESS_TOKEN")

# Create a new repository
repo = g.get_user().create_repo(name="NewRepository")
print(f"Repository created: {repo.full_name}")

9.8.7.2 - Fetching Repository Issues

Retrieve all open issues from a specified repository:

from github import Github

# Setup GitHub API client
g = Github("YOUR_ACCESS_TOKEN")

# Get repository
repo = g.get_repo("username/repository_name")

# Fetch issues
issues = repo.get_issues(state='open')
for issue in issues:
print(f"Issue #{issue.number}: {issue.title}")

9.8.7.3 - Managing User Profiles

Get information about a GitHub user and their repositories:

from github import Github

# Authenticate
g = Github("YOUR_ACCESS_TOKEN")

# Fetch user information
user = g.get_user("username")
print(f"User: {user.name}")
print("Repositories:")
for repo in user.get_repos():
print(repo.name)

9.8.8 - Utilizing the Amazon S3 API

Learn how to interact with Amazon S3 for object storage solutions.

9.8.8.1 - Uploading Files

Upload files to an S3 bucket:

import boto3

# Initialize S3 client
s3 = boto3.client('s3', aws_access_key_id='YOUR_ACCESS_KEY', aws_secret_access_key='YOUR_SECRET_KEY')

# Upload a file
s3.upload_file('file_name.txt', 'bucket_name', 'object_name')
print("File uploaded successfully.")

9.8.8.2 - Listing Bucket Contents

List all objects in a specific S3 bucket:

import boto3

# Setup S3 client
s3 = boto3.client('s3', aws_access_key_id='YOUR_ACCESS_KEY', aws_secret_access_key='YOUR_SECRET_KEY')

# List objects in a bucket
objects = s3.list_objects_v2(Bucket='bucket_name')
for item in objects.get('Contents', []):
print(f"File: {item['Key']} Size: {item['Size']}")

9.8.8.3 - Deleting Objects

Delete an object from an S3 bucket:

import boto3

# Connect to S3
s3 = boto3.client('s3', aws_access_key_id='YOUR_ACCESS_KEY', aws_secret_access_key='YOUR_SECRET_KEY')

# Delete an object
s3.delete_object(Bucket='bucket_name', Key='object_name')
print("Object deleted.")

9.8.9 - Working with the Microsoft Azure Cognitive Services API

Explore how to use Microsoft Azure's Cognitive Services to enhance applications with AI capabilities such as computer vision and text analytics.

9.8.9.1 - Analyzing Text Sentiment

Analyze the sentiment of text using the Text Analytics API:

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Setup credentials and client
credential = AzureKeyCredential("YOUR_COGNITIVE_SERVICES_KEY")
text_analytics_client = TextAnalyticsClient(endpoint="https://YOUR_ENDPOINT.cognitiveservices.azure.com/", credential=credential)

# Analyze sentiment
documents = ["I had the best day of my life", "This was the worst movie I have ever seen"]
response = text_analytics_client.analyze_sentiment(documents=documents)

# Display results
for document in response:
print(f"Document sentiment: {document.sentiment}")
for idx, sentence in enumerate(document.sentences):
print(f"Sentence {idx + 1}: {sentence.text}, Sentiment: {sentence.sentiment}")

9.8.9.2 - Recognizing Entities

Extract and categorize entities from text:

# Use previously configured credentials and client
documents = ["Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."]
response = text_analytics_client.recognize_entities(documents=documents)

# Process entity recognition results
for document in response:
for entity in document.entities:
print(f"Entity: {entity.text}, Type: {entity.category}, Subtype: {entity.subcategory}, Confidence Score: {entity.confidence_score}")

9.8.10 - Using the PayPal API

Integrate PayPal to manage payments, refunds, and transaction history in your applications.

9.8.10.1 - Processing Payments

Process payments through PayPal:

import paypalrestsdk
from paypalrestsdk import Payment

# Configure SDK
paypalrestsdk.configure({
"mode": "sandbox", # sandbox or live
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET"
})

# Create and process payment
payment = Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"},
"transactions": [{
"amount": {
"total": "30.11",
"currency": "USD"},
"description": "payment description"}],
"redirect_urls": {
"return_url": "http://localhost:3000/process",
"cancel_url": "http://localhost:3000/cancel"}})

# Create Payment
if payment.create():
print("Payment created successfully")
else:
print(payment.error)

9.8.10.2 - Refunding Payments

Issue refunds for previous transactions:

from paypalrestsdk import Sale

# Configure SDK as previously
sale = Sale.find("SALE_ID")
refund = sale.refund({
"amount": {
"total": "5.00",
"currency": "USD"
}
})

# Process refund
if refund.success():
print("Refund processed successfully")
else:
print(refund.error)

9.8.11 - Harnessing the Stripe API

The Stripe API allows for managing payments, customer transactions, and automating billing processes in your applications.

9.8.11.1 - Creating Charges

Create a charge to a customer's credit card:

import stripe

# Set your secret key
stripe.api_key = "YOUR_STRIPE_SECRET_KEY"

# Create a charge
charge = stripe.Charge.create(
amount=2000, # Amount in cents
currency="usd",
source="tok_amex", # Use an obtained token
description="Charge for jane.doe@example.com"
)

print(f"Charge created: {charge['id']}")

9.8.11.2 - Managing Subscriptions

Set up and manage recurring payments with subscriptions:

# Create a new customer and subscribe them to a plan
customer = stripe.Customer.create(
email="jane.doe@example.com",
source="tok_amex" # obtained with Stripe.js
)

subscription = stripe.Subscription.create(
customer=customer.id,
items=[{'plan': 'plan_CBXbz9i7AIOTzr'}] # Replace with your plan ID
)

print(f"Subscription created for: {subscription['customer']} with status: {subscription['status']}")

9.8.12 - Interacting with the Twilio API

Twilio API provides capabilities for sending SMS, making voice calls, and other communication functions.

9.8.12.1 - Sending SMS Messages

Send an SMS to a phone number using Twilio:

from twilio.rest import Client

# Your Account SID from twilio.com/console
account_sid = "YOUR_ACCOUNT_SID"
# Your Auth Token from twilio.com/console
auth_token = "YOUR_AUTH_TOKEN"

client = Client(account_sid, auth_token)

message = client.messages.create(
to="+1234567890", # Replace with the recipient's number
from_="+0987654321", # Replace with your Twilio number
body="Hello from Python!")

print(f"Sent message: {message.sid}")

9.8.12.2 - Making Voice Calls

Initiate a voice call through Twilio's API:

# Using previously created Twilio client
call = client.calls.create(
to="+1234567890", # Replace with the recipient's number
from_="+0987654321", # Replace with your Twilio number
url="http://demo.twilio.com/docs/voice.xml" # A URL returning TwiML instructions
)

print(f"Placed call with ID: {call.sid}")

9.8.13 - Using the Facebook Graph API

Leverage the Facebook Graph API to manage social media content, retrieve data, and interact with the vast features of Facebook platforms.

9.8.13.1 - Posting to a Page

Automatically post content to a Facebook page:

import facebook

# Initialize the Facebook Graph API client
graph = facebook.GraphAPI(access_token="YOUR_ACCESS_TOKEN")

# Post a message to the page
post_id = graph.put_object(parent_object='me', connection_name='feed',
message='Hello, world!')

print(f"Post was published on Facebook Page with id {post_id['id']}")

9.8.13.2 - Fetching Page Insights

Retrieve analytics data for a Facebook page:

# Use the same Graph API client initialized
insights = graph.get_connections(id='YOUR_PAGE_ID', connection_name='insights',
metric='page_impressions,page_engagement',
period='week')

for insight in insights['data']:
print(f"{insight['name']} - {insight['values'][0]['value']}")

9.8.14 - Interacting with the LinkedIn API

Use the LinkedIn API to automate professional networking tasks and retrieve user data.

9.8.14.1 - Sharing Content

Share updates to LinkedIn profiles or pages:

import linkedin

# Configure LinkedIn API client
application = linkedin.LinkedInApplication(token='YOUR_ACCESS_TOKEN')

# Share an update
application.submit_share('Sharing on LinkedIn is easy!')

print("Content shared successfully on LinkedIn.")

9.8.14.2 - Retrieving Profile Data

Get professional profile details from LinkedIn:

# Fetch your own profile data
my_profile = application.get_profile()

print(f"LinkedIn Profile ID: {my_profile['id']} - Name: {my_profile['firstName']} {my_profile['lastName']}")

9.8.15 - Utilizing the Google Sheets API

Manage data within Google Sheets using its powerful API for read and write operations.

9.8.15.1 - Writing Data to Sheets

Insert data into a Google Sheet:

from googleapiclient.discovery import build
from google.oauth2 import service_account

# Authentication and setup
SERVICE_ACCOUNT_FILE = 'path/to/service.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)

service = build('sheets', 'v4', credentials=creds)

# The ID of the spreadsheet
spreadsheet_id = 'YOUR_SPREADSHEET_ID'
range_name = 'Sheet1!A1'
value_input_option = 'USER_ENTERED'

# Values to be inserted
values = [
[
# Cell values ...
'Hello', 'World!'
],
# Additional rows ...
]
body = {
'values': values
}

# Call the Sheets API
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id, range=range_name,
valueInputOption=value_input_option, body=body).execute()

print(f"{result.get('updatedCells')} cells updated.")

9.8.15.2 - Reading Data from Sheets

Read data back from a Google Sheet:

result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id,
range="Sheet1!A1:C2").execute()
rows = result.get('values', [])

if not rows:
print('No data found.')
else:
for row in rows:
# Print columns A and B, which correspond to indices 0 and 1.
print(f"{row[0]}, {row[1]}")

9.8.16 - Accessing the Instagram Basic Display API

Fetch data and manage Instagram user profiles effectively using their Basic Display API.

9.8.16.1 - Getting User Media

Retrieve media items from an Instagram profile:

import requests

# Your Instagram app's access token
access_token = 'YOUR_ACCESS_TOKEN'
url = f"https://graph.instagram.com/me/media?fields=id,caption&access_token={access_token}"

# Make the API call
response = requests.get(url)
data = response.json()

for item in data['data']:
print(f"Media ID: {item['id']}, Caption: {item.get('caption', 'No caption provided')}")

9.8.16.2 - Refreshing Access Tokens

Extend the life of Instagram access tokens:

refresh_url = f"https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token={access_token}"
refresh_response = requests.get(refresh_url)
new_token =

refresh_response.json()['access_token']

print(f"Refreshed Access Token: {new_token}")

9.8.17 - Implementing the Trello API

Utilize the Trello API to automate task management and project tracking on Trello boards.

9.8.17.1 - Creating Cards

Add new cards to a Trello board programmatically:

import requests

# Setup authentication and endpoint
api_key = 'YOUR_API_KEY'
token = 'YOUR_TOKEN'
url = "https://api.trello.com/1/cards"

# Prepare the request parameters
query = {
'key': api_key,
'token': token,
'idList': 'YOUR_LIST_ID', # ID of the Trello list where the card will be added
'name': 'New Task', # Name of the card
'desc': 'Description of the task' # Description of the card
}

# Send the request
response = requests.post(url, params=query)
data = response.json()

print(f"Card created with ID: {data['id']} on list: {data['idList']}")

9.8.17.2 - Updating Board Lists

Move cards between lists on a Trello board:

# Move a card to a different list
move_url = f"https://api.trello.com/1/cards/{data['id']}/idList"

move_query = {
'key': api_key,
'token': token,
'value': 'NEW_LIST_ID' # ID of the new list to which the card will be moved
}

move_response = requests.put(move_url, params=move_query)
print("Card moved successfully.")

9.8.18 - Using the Dropbox API

The Dropbox API facilitates file management operations such as uploading, downloading, and syncing files across devices.

9.8.18.1 - Uploading Files to Dropbox

Upload files from your computer to a Dropbox account:

import dropbox

# Initialize the Dropbox client
dbx = dropbox.Dropbox('YOUR_ACCESS_TOKEN')

# File to be uploaded
file_path = '/path/to/your/file.txt'
destination_path = '/Apps/YourAppName/file.txt' # Path in Dropbox

with open(file_path, "rb") as f:
# Upload the file
dbx.files_upload(f.read(), destination_path, mode=dropbox.files.WriteMode("overwrite"))
print(f"File uploaded to {destination_path}")

9.8.18.2 - Listing Files in a Folder

Retrieve a list of files within a specific Dropbox folder:

# List files in a Dropbox directory
response = dbx.files_list_folder('/Apps/YourAppName')

for file in response.entries:
print(f"File: {file.name}, Type: {type(file).__name__}")