LoginSignup
9
14

More than 5 years have passed since last update.

Python3でAPIを叩くサンプル

Last updated at Posted at 2018-10-02

やること

Python3でRest Countries API から国コードを取得してくる。

環境

  • Mac OS X 10.14
  • Python3

準備

$ brew install python3

$ python -V

でPython3が返ってくることを確認します。

$ pip3 install requests

pip3でrequestsモジュールもインストールしておく

実装

$ vi test.py

viでtest.pyを作成して、編集する。

import requests
import json

# エンドポイント
url = 'https://restcountries.eu/rest/v2/all'
# リクエスト
res = requests.get(url)
# 取得したjsonをlists変数に格納
lists = json.loads(res.text)

for list in lists:
    print(list['name'] + ': ' + list['alpha2Code'])

以上が入力出来たら、以下で実行してみます。

$ python3 test.py

すると以下のように出力されるかと思います

Screen Shot 2018-10-02 at 11.46.26.png

簡単にAPIからデータを取得できました。

9
14
1

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
9
14