2025年にPythonでAPIコールをする方法

最新のGET/POSTテクニックを学び、JSONを解析し、効率的なPython API呼び出しのためにSDKを活用します。
8 分読
How to make API calls using Python blog image

このガイドでは、Pythonを使ったAPIの使い方について、以下の概念を説明します:

  1. HTTPとは何か?
  2. REST APIとは何か?
  3. GETリクエストの方法
  4. POSTリクエストの作り方
  5. SDKの使い方

HTTPとは何か?

HTTP(ハイパーテキスト・トランスファー・プロトコル)は、ほとんどのデータがウェブを移動する際の標準です。データベースがほとんどのウェブサイトのバックエンドを構成していると聞いたことがあると思いますが、これは事実です。しかし、クライアント(ブラウザやPythonスクリプト)が実際にどのようにデータベースとやりとりするかには微妙な違いがあります。HTTPはクライアントとバックエンドサーバー間の通信レイヤーです。

スクレイピングやウェブAPIにHTTPを使う場合、これらの方法を使うことが多い。

  • GET:最もよく使われる方法。サイトにアクセスするたびに、ブラウザはHTMLをGETし、ページを表示します。
  • POST:これは2番目に一般的な方法である。POSTは、より大きなデータを安全に転送するために使用され、ほとんどの場合、データベースに何かを追加するために使用されます。フォームやアンケートに回答したり、ソーシャルメディアに投稿したりするときは、POSTリクエストを行っていることになります。
  • PUT:PUTリクエストは、データベース内の既存のアイテムを更新するために使用される。あなたがソーシャルメディアの投稿を編集するとき、PUTはフードの下で使われる。
  • DELETE: ソーシャルメディアの投稿(またはデータベースからのその他のもの)を削除したい場合、ブラウザはサーバーにDELETEリクエストを送信して削除します。

HTTPとそのリターン・スタンダードの欠如

HTTPはそのシンプルさゆえに、普遍的な戻り値の標準を欠いている。デフォルトでHTMLを返すサーバーもあれば、JSONや、XMLやプレーンテキストのようなレガシーなデータ構造を返すサーバーもある。

まず、基本的なGETリクエストをしてみましょう。Python Requestsがまだインストールされていない場合は、pip経由でインストールできます。

pip install requests

Requestsをインストールしたら、以下のコードを実行して簡単なGETを行うことができる。ターミナルの出力に注目してください。

import requests

response = requests.get("https://quotes.toscrape.com")

print(response.text)

コードを実行すると、HTMLページができていることに気づくはずだ。ブラウザで見る分にはいいが、ターミナルで見るとかなり醜い。下の出力はトリミングされているが、おわかりいただけるだろう。

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>Quotes to Scrape</title>
    <link rel="stylesheet" href="/static/bootstrap.min.css">
    <link rel="stylesheet" href="/static/main.css">


</head>
<body>
    <div class="container">
        <div class="row header-box">
            <div class="col-md-8">
                <h1>
                    <a href="/" style="text-decoration: none">Quotes to Scrape</a>
                </h1>
            </div>
            <div class="col-md-4">
                <p>

                    <a href="/login">Login</a>

                </p>
            </div>
        </div>


<div class="row">
    <div class="col-md-8">

    <div class="quote" itemscope itemtype="http://schema.org/CreativeWork">
        <span class="text" itemprop="text">“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”</span>
        <span>by <small class="author" itemprop="author">Albert Einstein</small>
        <a href="/author/Albert-Einstein">(about)</a>
        </span>
        <div class="tags">
            Tags:
            <meta class="keywords" itemprop="keywords" content="change,deep-thoughts,thinking,world" /    >

            <a class="tag" href="/tag/change/page/1/">change</a>

            <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a>

            <a class="tag" href="/tag/thinking/page/1/">thinking</a>

            <a class="tag" href="/tag/world/page/1/">world</a>

        </div>
    </div>

    <div class="quote" itemscope itemtype="http://schema.org/CreativeWork">
        <span class="text" itemprop="text">“It is our choices, Harry, that show what we truly are, far more than our abilities.”</span>
        <span>by <small class="author" itemprop="author">J.K. Rowling</small>
        <a href="/author/J-K-Rowling">(about)</a>
        </span>
        <div class="tags">
            Tags:
            <meta class="keywords" itemprop="keywords" content="abilities,choices" /    >

            <a class="tag" href="/tag/abilities/page/1/">abilities</a>

            <a class="tag" href="/tag/choices/page/1/">choices</a>

        </div>
    </div>

HTMLページは、ブラウザが読んでレンダリングするためのものです。あなたが読んだり、あなたのコードに組み込んだりするためのものではありません。

REST(表現的状態遷移)はどのようにこれを解決するか

REST APIはデータパイプラインの設計基準を与えてくれる。JSONは、REST APIで最もよく使われる戻り値の型だ。柔軟で読みやすい。この明確で読みやすい構文は、プログラミング環境からの解析も容易にします。

JSONが実際にどのように見えるか、以下を見てみよう。このようなデータ構造を取得するためにREST APIを使用していることを忘れないでください。

{
    "name": "Jake",
    "age": 34,
    "professions": ["writing", "coding"]
}

REST APIは、エンドポイント、パラメータ、HTTPメソッドを使用して、返されるデータとそのフォーマットを制御する。

最初のAPIリクエスト

REST APIが何をするものかわかったところで、実際に使ってみよう。Quotes to ScrapeにもREST APIがある。単純にホームページを取得するのではなく、APIにアクセスしてみよう。エンドポイントを通してサーバーと通信するのだ。

私たちの完全なエンドポイント/api/quotesは、2つの部分に分けることができます。

  1. /api:これは、HTMLページではなく、構造化されたAPIデータが欲しいことをサーバーに伝える。
  2. /quotes:APIがquotesエンドポイントからデータを返すようにしたい。

リクエスト

前と同じようにコードを実行してください。

import requests
import json

response = requests.get("https://quotes.toscrape.com/api/quotes")

print(json.dumps(response.json(), indent=4))

データはきれいに構造化されて戻ってくる。解析は簡単で、そこからあらゆることができるようになる。

{
    "has_next": true,
    "page": 1,
    "quotes": [
        {
            "author": {
                "goodreads_link": "/author/show/9810.Albert_Einstein",
                "name": "Albert Einstein",
                "slug": "Albert-Einstein"
            },
            "tags": [
                "change",
                "deep-thoughts",
                "thinking",
                "world"
            ],
            "text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d"    
        },
        {
            "author": {
                "goodreads_link": "/author/show/1077326.J_K_Rowling",
                "name": "J.K. Rowling",
                "slug": "J-K-Rowling"
            },
            "tags": [
                "abilities",
                "choices"
            ],
            "text": "\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/9810.Albert_Einstein",
                "name": "Albert Einstein",
                "slug": "Albert-Einstein"
            },
            "tags": [
                "inspirational",
                "life",
                "live",
                "miracle",
                "miracles"
            ],
            "text": "\u201cThere are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/1265.Jane_Austen",
                "name": "Jane Austen",
                "slug": "Jane-Austen"
            },
            "tags": [
                "aliteracy",
                "books",
                "classic",
                "humor"
            ],
            "text": "\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/82952.Marilyn_Monroe",
                "name": "Marilyn Monroe",
                "slug": "Marilyn-Monroe"
            },
            "tags": [
                "be-yourself",
                "inspirational"
            ],
            "text": "\u201cImperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.\u201d"        
        },
        {
            "author": {
                "goodreads_link": "/author/show/9810.Albert_Einstein",
                "name": "Albert Einstein",
                "slug": "Albert-Einstein"
            },
            "tags": [
                "adulthood",
                "success",
                "value"
            ],
            "text": "\u201cTry not to become a man of success. Rather become a man of value.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/7617.Andr_Gide",
                "name": "Andr\u00e9 Gide",
                "slug": "Andre-Gide"
            },
            "tags": [
                "life",
                "love"
            ],
            "text": "\u201cIt is better to be hated for what you are than to be loved for what you are not.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/3091287.Thomas_A_Edison",
                "name": "Thomas A. Edison",
                "slug": "Thomas-A-Edison"
            },
            "tags": [
                "edison",
                "failure",
                "inspirational",
                "paraphrased"
            ],
            "text": "\u201cI have not failed. I've just found 10,000 ways that won't work.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/44566.Eleanor_Roosevelt",
                "name": "Eleanor Roosevelt",
                "slug": "Eleanor-Roosevelt"
            },
            "tags": [
                "misattributed-eleanor-roosevelt"
            ],
            "text": "\u201cA woman is like a tea bag; you never know how strong it is until it's in hot water.\u201d"
        },
        {
            "author": {
                "goodreads_link": "/author/show/7103.Steve_Martin",
                "name": "Steve Martin",
                "slug": "Steve-Martin"
            },
            "tags": [
                "humor",
                "obvious",
                "simile"
            ],
            "text": "\u201cA day without sunshine is like, you know, night.\u201d"
        }
    ],
    "tag": null,
    "top_ten_tags": [
        [
            "love",
            14
        ],
        [
            "inspirational",
            13
        ],
        [
            "life",
            13
        ],
        [
            "humor",
            12
        ],
        [
            "books",
            11
        ],
        [
            "reading",
            7
        ],
        [
            "friendship",
            5
        ],
        [
            "friends",
            4
        ],
        [
            "truth",
            4
        ],
        [
            "simile",
            3
        ]
    ]
}

認証されたリクエストを行う

公開データをリクエストする方法を見てきたところで、認証されたAPIを見てみよう。多くの場合、データを取得するにはAPIキーが必要だ。ほとんどのAPIサーバーは、リクエストを認証するためにAPIキーを含むAuthorizationヘッダーを要求する。

基本的なGETリクエストはとても簡単です。では、POSTリクエストをしてみましょう。POSTリクエストは、より大きなペイロードの情報を安全に扱うために使われる。以下のコードでは、Web UnlockerAPIを使ってページを解析し、マークダウンを返している。

import requests

API_KEY = "your-api-key"
ZONE = "web_unlocker1"

url = "https://api.brightdata.com/request"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}
payload = {
    "url": "https://quotes.toscrape.com/",
    "zone": ZONE,
    "format": "raw",
    "data_format": "markdown"
}

response = requests.post(url, headers=headers, json=payload)

print(response.text)

今回のリクエストはhttps://api.brightdata.com/request。すべてはヘッダーと ペイロードによって制御される。

これがヘッダーだ:

  • "Authorization": f "ベアラ {API_KEY}":これはリクエストを Bright Data アカウントに紐付けます。
  • "Content-Type":"application/json":これは、JSON形式でデータを送信することをサーバーに伝えます。

さて、ペイロードを見てみよう:

  • url":Web UnlockerでアクセスしたいURL。
  • "zone":Web Unlockerのインスタンスに与えたゾーン名。
  • "フォーマット":欲しいレスポンスのフォーマット(この場合は raw)
  • "data_format":markdown “を使用しています。これはBright Dataに、ページをmarkdown形式にパースしてほしいことを伝えます。JSONほど柔軟ではありませんが、簡単にJSONに変換できます。

ページがマークダウンに変換されたターミナル出力はこうだ。

# [Quotes to Scrape](/) 

[Login](/login)

“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” by Albert Einstein [(about)](/author/Albert-Einstein)

 Tags: [change](/tag/change/page/1/) [deep-thoughts](/tag/deep-thoughts/page/1/) [thinking](/tag/thinking/page/1/) [world](/tag/world/page/1/)

“It is our choices, Harry, that show what we truly are, far more than our abilities.” by J.K. Rowling [(about)](/author/J-K-Rowling)

 Tags: [abilities](/tag/abilities/page/1/) [choices](/tag/choices/page/1/)

“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.” by Albert Einstein [(about)](/author/Albert-Einstein)

 Tags: [inspirational](/tag/inspirational/page/1/) [life](/tag/life/page/1/) [live](/tag/live/page/1/) [miracle](/tag/miracle/page/1/) [miracles](/tag/miracles/page/1/)

“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.” by Jane Austen [(about)](/author/Jane-Austen) 

 Tags: [aliteracy](/tag/aliteracy/page/1/) [books](/tag/books/page/1/) [classic](/tag/classic/page/1/) [humor](/tag/humor/page/1/)

“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.” by Marilyn Monroe [(about)](/author/Marilyn-Monroe)

 Tags: [be-yourself](/tag/be-yourself/page/1/) [inspirational](/tag/inspirational/page/1/)

“Try not to become a man of success. Rather become a man of value.” by Albert Einstein [(about)](/author/Albert-Einstein)

 Tags: [adulthood](/tag/adulthood/page/1/) [success](/tag/success/page/1/) [value](/tag/value/page/1/)

“It is better to be hated for what you are than to be loved for what you are not.” by André Gide [(about)](/author/Andre-Gide)

 Tags: [life](/tag/life/page/1/) [love](/tag/love/page/1/)

“I have not failed. I've just found 10,000 ways that won't work.” by Thomas A. Edison [(about)](/author/Thomas-A-Edison)

 Tags: [edison](/tag/edison/page/1/) [failure](/tag/failure/page/1/) [inspirational](/tag/inspirational/page/1/) [paraphrased](/tag/paraphrased/page/1/)

“A woman is like a tea bag; you never know how strong it is until it's in hot water.” by Eleanor Roosevelt [(about)](/author/Eleanor-Roosevelt)        

 Tags: [misattributed-eleanor-roosevelt](/tag/misattributed-eleanor-roosevelt/page/1/)

“A day without sunshine is like, you know, night.” by Steve Martin [(about)](/author/Steve-Martin)

 Tags: [humor](/tag/humor/page/1/) [obvious](/tag/obvious/page/1/) [simile](/tag/simile/page/1/)

* [Next →](/page/2/)

## Top Ten tags

[love](/tag/love/) [inspirational](/tag/inspirational/) [life](/tag/life/) [humor](/tag/humor/) [books](/tag/books/) [reading](/tag/reading/) [friendship](/tag/friendship/) [friends](/tag/friends/) [truth](/tag/truth/) [simile](/tag/simile/)

 Quotes by: [GoodReads.com](https://www.goodreads.com/quotes)

 M

認証には一意の識別子(通常はAPIキー)を使う。今回はWeb Unlockerにアクセスしたが、どのAPIサービスを使っても原理は同じだ。

レスポンスへの対応

各レスポンスにはステータスコードが含まれる。ステータスコードは、さまざまなメッセージをクライアントに返すために使用されます。完璧な世界では、常に200ステータスを受け取ります。

悲しいことに、世の中は完璧ではありません。200以外のコードが表示された場合は、何かが間違っていることを意味します。

  • 400-499:これらのコードは通常、クライアント側のエラーを意味します。APIキーとリクエストフォーマットを再度確認してください。
  • 500-599:この範囲はサーバーエラーを示します。リクエストは正常でしたが、サーバーが何らかの理由でリクエストを完了できませんでした。

ステータスコードについてはこちらで詳しく説明しています。Python からこれらのステータスコードを扱う方法を学びたい場合は、再試行ロジックに関するガイドを見てください。

SDKでボイラープレートをスキップする

SDK(ソフトウェア開発キット)を使えば、エラー処理や再試行ロジックのための定型文を書かなくても、REST APIに接続できる。OpenAI APIは完全なREST APIも提供している。こちらをご覧ください。

SDKをインストールしてHTTPリクエストをスキップするには、以下のコマンドを実行する。

pip install openai

ここで、OpenAI SDKをインポートします。最初にやったように、古いHTMLページを取得する。HTMLを手動でパースすることに興味があれば、BeautifulSoupでRequestsを使う方法を学ぶことができます。HTMLページを取得したら、SDKを使ってChatGPTにページを渡してパースします。

from openai import OpenAI
import requests

OPENAI_API_KEY = "sk-your-openai-api-key"

response = requests.get("https://quotes.toscrape.com")
html_page = response.text

client = OpenAI(api_key=OPENAI_API_KEY)

chat = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": f"Parse the quotes from the following page. I want JSON only--zero commentary from you, here's the page: {html_page}",
        }
    ],
    model="gpt-4o-mini",
)

reply = chat.choices[0].message.content
print(f"ChatGPT: {reply}")

今回の出力を見てみよう。パース不要、jsonブロックの中のデータだけです。

[
    {
        "text": "The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.",
        "author": "Albert Einstein",
        "tags": ["change", "deep-thoughts", "thinking", "world"]
    },
    {
        "text": "It is our choices, Harry, that show what we truly are, far more than our abilities.",
        "author": "J.K. Rowling",
        "tags": ["abilities", "choices"]
    },
    {
        "text": "There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.",   
        "author": "Albert Einstein",
        "tags": ["inspirational", "life", "live", "miracle", "miracles"]
    },
    {
        "text": "The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.",
        "author": "Jane Austen",
        "tags": ["aliteracy", "books", "classic", "humor"]
    },
    {
        "text": "Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.",
        "author": "Marilyn Monroe",
        "tags": ["be-yourself", "inspirational"]
    },
    {
        "text": "Try not to become a man of success. Rather become a man of value.",
        "author": "Albert Einstein",
        "tags": ["adulthood", "success", "value"]
    },
    {
        "text": "It is better to be hated for what you are than to be loved for what you are not.",
        "author": "André Gide",
        "tags": ["life", "love"]
    },
    {
        "text": "I have not failed. I've just found 10,000 ways that won't work.",
        "author": "Thomas A. Edison",
        "tags": ["edison", "failure", "inspirational", "paraphrased"]
    },
    {
        "text": "A woman is like a tea bag; you never know how strong it is until it's in hot water.",
        "author": "Eleanor Roosevelt",
        "tags": ["misattributed-eleanor-roosevelt"]
    },
    {
        "text": "A day without sunshine is like, you know, night.",
        "author": "Steve Martin",
        "tags": ["humor", "obvious", "simile"]
    }
]

SDKは、手動でHTTPを管理することなく、REST APIのフルパワーを提供します。AIを使ったスクレイピングに興味がある方は、Claudeと DeepSeekのガイドをご覧ください。

結論

Pythonを使った基本的なAPIリクエストの作り方がわかったところで、より大きなプロジェクトに進むことができる。APIを使って様々なサービスとやり取りしてデータを取得したり、SDKを利用してデータを自動的に解析することもできます。このチュートリアルではWeb Unlockerを使用しましたが、Bright Dataはあなたのデータニーズを助ける様々な製品を提供しています。

  • レジデンシャル・プロキシ:住宅用IPアドレスを持つ実際のデバイスを経由してHTTPトラフィックをルーティングします。
  • スクレイパーAPI:スクレイピングを完全に自動化し、結果をあなたのプログラミング環境に直接ダウンロードします。
  • スクレイピング・ブラウザ:CAPTCHAを回避し、Pythonスクリプトの内部から本物のヘッドレスブラウザを制御します。

無料トライアルに登録して、今すぐ始めましょう!

クレジットカードは必要ありません