0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WebAPIをたたく with Python

Last updated at Posted at 2021-11-24

PythonでWebAPIを叩く方法を簡潔に紹介します。

使用するAPI

ここではNews APIを扱います。News APIでは世界中のニュースを取得することができます。また、個人で利用する分には十分無料で使えます。

今回はAPIを叩くことだけが目的なので、News APIの使い方には言及していません。

実際のコード

import requests

# News APIに登録した際に発行される自分用のAPI KEY
API_KEY = 'Your API KEY'

# APIを叩く!!
res = requests.get(f'https://newsapi.org/v2/everything?q=bitcoin&apiKey={API_KEY}')
res_obj = res.json() # json形式に変換
print(res.status_code) # 200が返ればOK
print(res_obj)

エンドポイント

特定のリソースに対して与えられた固有の一意なURLのことです。今回の例でいうと、以下に示すように ? の手前までのURLです。

https://newsapi.org/v2/everything

パラメータ

ほしい情報を取得するための条件のようなもののことです。今回の例でいうと、2つのパラメータ(q, apiKey)が与えられています。パラメータどうしは & でつなげます。

q=bitcoin&apiKey={API_KEY}

出力例

以下のような出力が得られれば大丈夫です。

200
{
    "status": "ok",
    "totalResults": 8069,
    "articles": [
        {
            "source": {
            "id": "the-verge",
            "name": "The Verge"
            },
            "author": "Richard Lawler",
            "title": "A fake press release claiming Kroger accepts crypto reached the retailer’s own webpage",
            "description": "A crypto hoax claimed Kroger is accepting Bitcoin Cash. The fake press release was similar to one targeting Walmart earlier this year. The retailer quickly confirmed it’s fake, but not before the cryptocurrency’s price spiked by $30.",
            "url": "https://www.theverge.com/2021/11/5/22765098/kroger-bitcoin-cash-cryptocurrency-hoax-pump-dump",
            "urlToImage": "https://cdn.vox-cdn.com/thumbor/CKp0YjnwF88--mWg1kfPmspvfzY=/0x358:5000x2976/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/22988084/1234440443.jpg",
            "publishedAt": "2021-11-05T13:32:14Z",
            "content": "A similar hoax earlier this year tied Walmart to Litecoin\r\nIf you buy something from a Verge link, Vox Media may earn a commission. See our ethics statement.\r\nPhoto Illustration by Thiago Prudencio/S… [+1900 chars]"
        },
        {
            "source": {
            # 省略

さいごに

以上がWebAPIをPythonで叩く方法になります。

APIに関してはもっと深く掘り下げて説明しようとすると、HTTP、ステータスコード、REST APIなど取り上げるべき話がたくさんあります。ただし今回はあくまでもWebAPIをどうやって叩くのかだけに注力したかった(ダラダラと長い記事を書きたくない)のでここで締めます。

それではよい1日を!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?