ななぶろ

-お役立ち情報を気楽に紹介するブログ-

Pythonプログラム練習問題10問:APIを活用してスキルアップ!

www.amazon.co.jp

Pythonプログラム練習問題10問:APIを活用してスキルアップ!

Pythonは汎用性の高いプログラミング言語であり、その強力なライブラリとフレームワークの豊富さも魅力の一つです。特に、API(Application Programming Interface)を利用することで、外部サービスやデータにアクセスし、独自のアプリケーションを構築することができます。

本記事では、PythonでAPIを活用するスキルを向上させるための練習問題10問を紹介します。初心者から中級者まで対応できるよう、難易度も様々です。各問題には解説とサンプルコードを記載しているので、ぜひ挑戦してみてください。

APIとは?

まず、APIについて簡単に説明します。APIは、異なるソフトウェアやシステムが互いに通信し、データを交換するためのインターフェースです。例えば、Google Maps APIを利用すれば、地図情報を自分のアプリケーションに組み込むことができます。Twitter APIを使えば、ツイートを取得したり投稿したりできます。APIは、まるでレストランのウェイターのように、クライアント(あなたのプログラム)とサーバー(外部サービス)の間を取り持ち、リクエストを受け取り、必要なデータを提供します。

APIには様々な種類がありますが、Web APIとして広く利用されているのはRESTful APIです。RESTful APIは、HTTPメソッド(GET, POST, PUT, DELETEなど)を用いてリクエストを送信し、JSONやXMLなどの形式でレスポンスを受け取ります。

  • GET: データを取得するために使用されます。
  • POST: 新しいデータを作成するために使用されます。
  • PUT: 既存のデータを更新するために使用されます。
  • DELETE: データを削除するために使用されます。

JSON (JavaScript Object Notation) は、人間にも機械にも読みやすい軽量なデータ交換フォーマットです。XML (Extensible Markup Language) も同様にデータ交換に使用されますが、JSONの方がよりシンプルで使いやすい傾向があります。

準備するもの

これらの練習問題を解くために必要なものは以下の通りです。

  • Python環境: Python 3.6以上が推奨されます。Pythonのインストール方法については、https://www.python.org/downloads/ を参照してください。
  • requestsライブラリ: HTTPリクエストを送信するためのライブラリです。pip install requestsでインストールできます。ターミナルまたはコマンドプロンプトでこのコマンドを実行することで、requestsライブラリがあなたのPython環境にインストールされます。
  • APIキー(必要に応じて): 一部のAPIは、利用するためにAPIキーが必要です。各APIのドキュメントを参照して取得してください。APIキーは、あなたがそのAPIを利用していることを証明するための認証情報です。

練習問題10選

それでは、PythonでAPIを活用する練習問題を10問紹介します。

1. 天気情報を取得する (難易度: 簡単)

OpenWeatherMap APIを利用して、指定した都市の天気情報を取得します。

  • APIドキュメント: https://openweathermap.org/api
  • 手順:
    1. OpenWeatherMapに登録し、APIキーを取得します。無料プランでも十分です。
    2. requestsライブラリを使ってAPIにリクエストを送信します。
    3. JSON形式のレスポンスを解析し、天気情報(気温、湿度、降水確率など)を表示します。
import requests
import json

def get_weather(city, api_key):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url)
    data = response.json()

    if data["cod"] == 200:
        temperature = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        description = data["weather"][0]["description"]
        print(f"天気:{description}")
        print(f"気温:{temperature}°C")
        print(f"湿度:{humidity}%")
    else:
        print("エラー:", data["message"])

# APIキーをここに設定
api_key = "YOUR_API_KEY"  # 実際のAPIキーに置き換えてください
city = "Tokyo"
get_weather(city, api_key)
  • Explanation: This code retrieves weather information for a given city using the OpenWeatherMap API. It first constructs the URL with the city name and API key. Then, it sends a GET request to the API endpoint. If the response status code is 200 (OK), it parses the JSON data and extracts temperature, humidity, and description. Otherwise, it prints an error message. Remember to replace "YOUR_API_KEY" with your actual API key from OpenWeatherMap.

2. GitHubのレポジトリ情報を取得する (難易度: 簡単)

GitHub APIを利用して、指定したユーザーのレポジトリ一覧を取得します。

  • APIドキュメント: https://docs.github.com/en/rest
  • 手順:
    1. requestsライブラリを使ってAPIにリクエストを送信します。
    2. JSON形式のレスポンスを解析し、レポジトリ名とURLを表示します。
import requests
import json

def get_github_repos(username):
    url = f"https://api.github.com/users/{username}/repos"
    response = requests.get(url)
    data = response.json()

    for repo in data:
        print(f"レポジトリ名:{repo['name']}")
        print(f"URL:{repo['html_url']}")

# ユーザー名をここに設定
username = "google"
get_github_repos(username)
  • Explanation: This code retrieves a list of repositories for a given GitHub username. It constructs the URL with the username and sends a GET request to the API endpoint. The response is parsed as JSON, and then it iterates through each repository in the data, printing its name and URL.

3. JSONPlaceholderからデータを取得する (難易度: 簡単)

JSONPlaceholderは、テストやプロトタイピング用の無料のオンラインREST APIです。

  • APIドキュメント: https://jsonplaceholder.typicode.com/
  • 手順:
    1. requestsライブラリを使ってAPIにリクエストを送信します。
    2. JSON形式のレスポンスを解析し、特定のデータを表示します(例:投稿の一覧、コメントの一覧など)。
import requests
import json

def get_posts():
    url = "https://jsonplaceholder.typicode.com/posts"
    response = requests.get(url)
    data = response.json()

    for post in data:
        print(f"タイトル:{post['title']}")
        print(f"本文:{post['body']}")
        print("-" * 20)

get_posts()
  • Explanation: This code retrieves a list of posts from the JSONPlaceholder API. It sends a GET request to the /posts endpoint and parses the JSON response. Then, it iterates through each post in the data, printing its title and body.

4. APIからデータをフィルタリングする (難易度: 普通)

上記のいずれかのAPIを利用して、特定の条件を満たすデータのみを取得します。例えば、GitHubのレポジトリ一覧から、特定の言語で書かれたレポジトリのみを取得するなどです。

  • ヒント: APIのリクエストパラメータを調整することで、データをフィルタリングできます。
import requests
import json

def get_github_repos_by_language(username, language):
    url = f"https://api.github.com/users/{username}/repos?language={language}"
    response = requests.get(url)
    data = response.json()

    for repo in data:
        print(f"レポジトリ名:{repo['name']}")
        print(f"URL:{repo['html_url']}")

# ユーザー名と言語を設定
username = "google"
language = "python"
get_github_repos_by_language(username, language)
  • Explanation: This code retrieves a list of repositories for a given GitHub username that are written in a specific programming language. It constructs the URL with the username and language parameter. The response is parsed as JSON, and then it iterates through each repository in the data, printing its name and URL.

5. APIにPOSTリクエストを送信する (難易度: 普通)

JSONPlaceholderのpostsエンドポイントに対して、新しい投稿を作成するためのPOSTリクエストを送信します。

  • 手順:
    1. requests.post()メソッドを使ってAPIにリクエストを送信します。
    2. リクエストボディにJSON形式でデータを記述します。
    3. レスポンスを確認し、作成された投稿のIDを表示します。
import requests
import json

def create_post(title, body):
    url = "https://jsonplaceholder.typicode.com/posts"
    data = {"title": title, "body": body, "userId": 1}
    response = requests.post(url, data=json.dumps(data))
    if response.status_code == 201:
        print("投稿が作成されました:", response.json()["id"])
    else:
        print("エラー:", response.status_code)

create_post("My New Post", "This is the body of my new post.")
  • Explanation: This code creates a new post on JSONPlaceholder using a POST request. It constructs the URL for the /posts endpoint and prepares a dictionary containing the title, body, and user ID. The json.dumps() function converts the Python dictionary into a JSON string, which is then sent as the data in the POST request. If the response status code is 201 (Created), it prints the ID of the newly created post.

6. APIのレスポンスをJSONで解析する (難易度: 普通)

APIから取得したレスポンスがJSON形式の場合、response.json()メソッドを使ってPythonの辞書やリストに変換します。この方法を用いて、特定のデータを抽出して表示します。

  • ヒント: JSONデータの構造を理解することが重要です。
import requests
import json

def get_user(username):
    url = f"https://api.github.com/users/{username}"
    response = requests.get(url)
    data = response.json()

    print(f"ユーザー名:{data['login']}")
    print(f"ID:{data['id']}")
    print(f"名前:{data['name']}")
    print(f"URL:{data['html_url']}")

get_user("google")
  • Explanation: This code retrieves information about a GitHub user using the API. It constructs the URL with the username and sends a GET request to the API endpoint. The response is parsed as JSON, and then it extracts specific fields like login (username), id, name, and html_url from the data dictionary.

7. エラーハンドリングを行う (難易度: 普通)

APIリクエストが失敗した場合(例:ネットワークエラー、APIキーの認証失敗など)、適切なエラー処理を行います。try-exceptブロックを使って例外を捕捉し、ユーザーに分かりやすいメッセージを表示します。

  • ヒント: response.status_code属性を使ってレスポンスステータスコードを確認できます。
import requests
import json

def get_data(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # ステータスコードが200番台でない場合は例外を発生させる
        return response.json()
    except requests.exceptions.RequestException as e:
        print("エラー:", e)
        return None

data = get_data("https://jsonplaceholder.typicode.com/posts")
if data:
    print(data[0]['title'])
  • Explanation: This code demonstrates error handling when making API requests. It uses a try-except block to catch potential exceptions that might occur during the request, such as network errors or invalid responses. The response.raise_for_status() method raises an exception if the response status code indicates an error (e.g., 404 Not Found, 500 Internal Server Error). If an error occurs, it prints an error message and returns None.

8. APIの認証を行う (難易度: 難しい)

一部のAPIは、利用するために認証が必要です。例えば、Basic AuthenticationやOAuthなどの認証方式があります。requestsライブラリを使って、これらの認証方式に対応したリクエストを送信します。

  • ヒント: APIのドキュメントを参照して、適切な認証方法を選択してください。
import requests
import json

def get_protected_resource(url, username, password):
    response = requests.get(url, auth=(username, password))
    if response.status_code == 200:
        return response.json()
    else:
        print("エラー:", response.status_code)
        return None

# Basic Authenticationの例
url = "https://httpbin.org/basic-auth/user/password"  # テスト用のURL
username = "user"
password = "password"

data = get_protected_resource(url, username, password)
if data:
    print(data)
  • Explanation: This code demonstrates how to use Basic Authentication with the requests library. It constructs a URL that requires authentication and provides the username and password as arguments to the auth parameter in the requests.get() method. If the request is successful (status code 200), it returns the JSON response; otherwise, it prints an error message.

9. 複数のAPIを組み合わせる (難易度: 難しい)

複数のAPIを利用して、より複雑な処理を行います。例えば、OpenWeatherMap APIで天気情報を取得し、その情報に基づいて他のAPIにリクエストを送信するなどです。

import requests
import json

def get_weather_and_related_data(city, api_key):
    # OpenWeatherMapから天気情報を取得
    weather_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    weather_response = requests.get(weather_url)
    weather_data = weather_response.json()

    if weather_data["cod"] == 200:
        temperature = weather_data["main"]["temp"]
        print(f"{city}の気温:{temperature}°C")

        # 気温に基づいて別のAPIにリクエストを送信 (例: ニュースAPI)
        news_url = f"https://newsapi.org/v2/top-headlines?country=jp&q={city}&apiKey=YOUR_NEWS_API_KEY" # 実際のAPIキーに置き換えてください
        news_response = requests.get(news_url)
        news_data = news_response.json()

        if news_data["status"] == "ok":
            print("関連ニュース:")
            for article in news_data["articles"]:
                print(f"- {article['title']}")
        else:
            print("ニュース取得に失敗しました。")
    else:
        print("天気情報の取得に失敗しました。")

# APIキーをここに設定
api_key = "YOUR_OPENWEATHERMAP_API_KEY" # 実際のAPIキーに置き換えてください
city = "Tokyo"
get_weather_and_related_data(city, api_key)
  • Explanation: This code combines two APIs: OpenWeatherMap and News API. It first retrieves weather information for a given city using the OpenWeatherMap API. Then, based on the temperature, it sends a request to the News API to retrieve news articles related to that city. This demonstrates how you can chain multiple API calls together to create more complex workflows.

10. 独自のAPIエンドポイントを作成する (難易度: 難しい)

FlaskやFastAPIなどのWebフレームワークを使って、独自のAPIエンドポイントを作成します。このエンドポイントは、他のアプリケーションからリクエストを受け取り、処理を行い、レスポンスを返します。

  • ヒント: Webフレームワークのドキュメントを参照し、基本的なAPIの作成方法を理解してください。
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api/data', methods=['GET'])
def get_data():
    # リクエストパラメータを取得
    param1 = request.args.get('param1')
    param2 = request.args.get('param2')

    # 処理を行う (例: データベースからデータを取得)
    result = {"message": f"param1={param1}, param2={param2}"}

    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True)
  • Explanation: This code creates a simple API endpoint using Flask. The @app.route() decorator defines the URL route for the endpoint (/api/data). The get_data() function handles incoming GET requests to this endpoint. It retrieves parameters from the request, performs some processing (in this case, just constructing a message), and returns a JSON response using jsonify().

まとめ

本記事では、PythonでAPIを活用する練習問題10問を紹介しました。これらの問題を解くことで、APIリクエストの送信、JSONデータの解析、エラーハンドリング、認証などのスキルを向上させることができます。

APIは、外部サービスやデータにアクセスし、独自のアプリケーションを構築するための強力なツールです。ぜひ、これらの練習問題を参考に、APIを活用したプログラミングに挑戦してみてください。

参考資料

これらの練習問題を通して、PythonとAPIの組み合わせの可能性を広げ、より高度なアプリケーション開発に挑戦してみてください。頑張ってください!


English Translation: 10 Python Programming Exercises: Level Up Your Skills by Utilizing APIs!

The content of this article introduces 10 practice problems for using APIs with Python. Python is a versatile programming language, and one of its appeals lies in the abundance of powerful libraries and frameworks available. In particular, utilizing APIs (Application Programming Interfaces) allows you to access external services and data and build your own unique applications.

This article introduces 10 practice problems designed to improve your skills in using APIs with Python. These range in difficulty from beginner to intermediate, so everyone can participate. Each problem includes explanations and sample code, so please give them a try.

What is an API?

Let's briefly explain what an API is. An API is an interface that allows different software or systems to communicate and exchange data with each other. For example, using the Google Maps API, you can incorporate map information into your application. Using the Twitter API, you can retrieve or post tweets.

There are various types of APIs, but RESTful APIs are widely used on the web. RESTful APIs use HTTP methods (GET, POST, PUT, DELETE, etc.) to send requests and receive responses in formats such as JSON or XML.

What You'll Need

Here’s what you need to solve these practice problems:

  • Python Environment: Python 3.6 or higher is recommended.
  • Requests Library: A library for sending HTTP requests. Install it with pip install requests.
  • API Key (as needed): Some APIs require an API key to use them. Obtain one by referring to the documentation of each API.

10 Practice Problems

Here are 10 practice problems introducing how to utilize APIs with Python:

1. Get Weather Information (Difficulty: Easy)

Use the OpenWeatherMap API to get weather information for a specified city.

  • API Documentation: https://openweathermap.org/api
  • Steps:
    1. Register with OpenWeatherMap and obtain an API key.
    2. Use the requests library to send a request to the API.
    3. Parse the JSON response and display weather information (temperature, humidity, probability of precipitation, etc.).
import requests
import json

def get_weather(city, api_key):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url)
    data = response.json()

    if data["cod"] == 200:
        temperature = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        description = data["weather"][0]["description"]
        print(f"Weather: {description}")
        print(f"Temperature: {temperature}°C")
        print(f"Humidity: {humidity}%")
    else:
        print("Error:", data["message"])

# Set your API key here
api_key = "YOUR_API_KEY"  # Replace with your actual API key
city = "Tokyo"
get_weather(city, api_key)

2. Get GitHub Repository Information (Difficulty: Easy)

Use the GitHub API to retrieve a list of repositories for a specified user.

  • API Documentation: https://docs.github.com/en/rest
  • Steps:
    1. Use the requests library to send a request to the API.
    2. Parse the JSON response and display the repository name and URL.
import requests
import json

def get_github_repos(username):
    url = f"https://api.github.com/users/{username}/repos"
    response = requests.get(url)
    data = response.json()

    for repo in data:
        print(f"Repository Name: {repo['name']}")
        print(f"URL: {repo['html_url']}")

# Set the username here
username = "google"
get_github_repos(username)

3. Get Data from JSONPlaceholder (Difficulty: Easy)

JSONPlaceholder is a free online REST API for testing and prototyping.

  • API Documentation: https://jsonplaceholder.typicode.com/
  • Steps:
    1. Use the requests library to send a request to the API.
    2. Parse the JSON response and display specific data (e.g., list of posts, list of comments).
import requests
import json

def get_posts():
    url = "https://jsonplaceholder.typicode.com/posts"
    response = requests.get(url)
    data = response.json()

    for post in data:
        print(f"Title: {post['title']}")
        print(f"Body: {post['body']}")
        print("-" * 20)

get_posts()

4. Filter Data from an API (Difficulty: Normal)

Using one of the above APIs, retrieve only data that meets specific criteria. For example, retrieving only repositories written in a specific language from GitHub's repository list.

  • Hint: You can filter data by adjusting the request parameters of the API.

5. Send a POST Request to an API (Difficulty: Normal)

Send a POST request to the posts endpoint of JSONPlaceholder to create a new post.

  • Steps:
    1. Use the requests.post() method to send a request to the API.
    2. Describe data in JSON format in the request body.
    3. Check the response and display the ID of the created post.
import requests
import json

def create_post(title, body):
    url = "https://jsonplaceholder.typicode.com/posts"
    data = {"title": title, "body": body, "userId": 1}
    response = requests.post(url, data=json.dumps(data))
    if response.status_code == 201:
        print("Post created:", response.json()["id"])
    else:
        print("Error:", response.status_code)

create_post("My New Post", "This is the body of my new post.")

6. Parse JSON Response from an API (Difficulty: Normal)

When the response received from an API is in JSON format, convert it to a Python dictionary or list using the response.json() method. Use this method to extract and display specific data.

  • Hint: Understanding the structure of the JSON data is important.

7. Implement Error Handling (Difficulty: Normal)

When an API request fails (e.g., network error, API key authentication failure), perform appropriate error handling. Use a try-except block to catch exceptions and display user-friendly messages.

  • Hint: You can check the response status code using the response.status_code attribute.
import requests
import json

def get_data(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception if the status code is not in the 200s
        return response.json()
    except requests.exceptions.RequestException as e:
        print("Error:", e)
        return None

data = get_data("https://jsonplaceholder.typicode.com/posts")
if data:
    print(data[0]['title'])

8. Perform API Authentication (Difficulty: Difficult)

Some APIs require authentication to use them. For example, there are authentication methods such as Basic Authentication and OAuth. Use the requests library to send requests that support these authentication methods.

  • Hint: Refer to the documentation of each API and select an appropriate authentication method.

9. Combine Multiple APIs (Difficulty: Difficult)

Perform more complex processing by using multiple APIs. For example, retrieve weather information with the OpenWeatherMap API and then send a request to another API based on that information.

  • Hint: Carefully read the documentation of each API and understand the flow of data.

10. Create Your Own API Endpoint (Difficulty: Difficult)

Create your own API endpoint using a web framework such as Flask or FastAPI. This endpoint receives requests from other applications, processes them, and returns responses.

  • Hint: Refer to the documentation of the web framework and understand how to create basic APIs.

Summary

This article introduced 10 practice problems for utilizing APIs with Python. By solving these problems, you can improve your skills in sending API requests, parsing JSON data, error handling, and authentication.

APIs are a powerful tool for accessing external services and data and building your own unique applications. Please try these practice problems and challenge yourself to programming that utilizes APIs.

References

Through these practice problems, expand the possibilities of combining Python and APIs and challenge yourself to more advanced application development. Good luck!