LoginSignup
4
4

More than 5 years have passed since last update.

PythonでWebAPIコール

Posted at

前回は呼び出される側のコードを書いたので、今回は呼び出す側

コード内で使用しているWebAPIは、livedoorの「Weather Hacks」
登録不要で使えます。
http://weather.livedoor.com/weather_hacks/webservice

ソースコード

call_web_api.py
# -*- coding: utf-8 -*-
import requests
import json

import sys
import codecs


if __name__ == "__main__":

    # WebAPIのURL
    # 天気予報取得(Weather Hacks : http://weather.livedoor.com/weather_hacks/webservice)
    base_url = "http://weather.livedoor.com/forecast/webservice/json/v1"

    # 天気予報を取得したい地点(http://weather.livedoor.com/forecast/rss/primary_area.xml)
    param_city = "?city=230010"

    # GET通信でリクエストを送り、レスポンスを受け取る
    response = requests.get(base_url + param_city)

    # レスポンスはJSON 読み込む
    data = json.loads(response.text, "utf-8")

    # JSONからタイトルと天気予報のテキスト取得
    title = data["title"]
    forecast_text = data["description"]["text"]

    # 自分の環境(Windows)だと文字化けするので
    sys.stdout = codecs.getwriter('shift-jis')(sys.stdout)

    # 出力
    print title
    print forecast_text

実行結果

改行は少し修正してます。

愛知県 名古屋 の天気
前線を伴った発達中の低気圧が福島県沖にあって北東に進んでいます。
一方、華中に中心をもつ高気圧が西日本に張り出しています。
東海地方は、晴れまたは曇りとなっています。
今夜の東海地方は、高気圧におおわれるため、おおむね晴れますが、岐阜県の飛騨地方では、寒気の影響で曇りとなるでしょう。
明日の東海地方は、高気圧におおわれるため、おおむね晴れますが、上空の気圧の谷や寒気の影響で雲が広がる所があるでしょう。

4
4
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
4
4