0
1

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 1 year has passed since last update.

Djangoメモ -API呼び出し編-

0
Last updated at Posted at 2025-10-21

はじめに

前回で一通りdjangoの使い方については書いたので、あとはそれらを使ってアプリを制作するだけです!!その中でも特に重要なのがAPIです。今回はそれについていじっていきたいと思います。

API導入

1,APIとは

そもそもAPIとは何ぞやって方もいると思うので、説明します。APIとはApplication Programming Interfaceの略であり、端的に言うとアプリ同士をつなぐためのものです。例えば、アプリ内でgoogleカレンダー入れるとそれはAPIを活用しているということです。

2,OpenWeatherAPIの利用

今回使っていくAPIは天気のAPIであるOpenWeatherAPIを使っていきます。
本来であれば、企業のサイトに行ってAPIの使い方などを見ながらやっていくのですが、今回はサイトが古くなってしまったのでコードだけ見せます。無料で問題なく使えるので大丈夫です。今回はJSON形式でレスポンスが返ってくるのでimport JSONをしてます

views.py
from django.shortcuts import render
import json
import urllib.request

# Create your views here.
def index(request):
    if request.method == 'POST':
        city = request.POST['city']
        res = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=cb771e45ac79a4e8e2205c0ce66ff633').read()
        json_data = json.loads(res)
        data = {
            "country_code": str(json_data['sys']['country']),
            "coordinate": str(json_data['coord']['lon']) + ' ' +
            str(json_data['coord']['lat']),
            "temp": str(json_data['main']['temp'])+'k',
            "pressure": str(json_data['main']['pressure']),
            "humidity": str(json_data['main']['humidity']),
        }

    else:
        city = ''
        data = {}
    return render(request, 'index.html', {'city': city, 'data': data})

3,JSONデータに慣れよう

JSONとは軽量で扱いやすいデータフォーマットです。JSONはkeyと値を" : "で対応させ、" , "で区切ります。中身の型は文字列、数値、null、bool値、オブジェクトが入れられます。
取り出し方は辞書型の中に辞書が入っている場合は順番にkeyを指定していけばよいです。試しに以下のJSONで練習してみましょう

ex.json
{
  "title": "ChatGPT",
  "description": "答えをその手に。ひらめきを感じて。生産性を新たな次元へ。",
  "features": [
    "無料でかんたんに使える",
    "文章作成や学び、アイデア出しをサポート",
    "高性能なAIチャットアシスタント"
  ],
  "actions": [
    {
      "label": "今すぐ始める",
      "url": "https://chatgpt.com"
    },
    {
      "label": "アプリをダウンロード",
      "url": "https://openai.com/ja-JP/chatgpt/overview/"
    }
  ]
}

単純にtitleである"chatgpt"を抽出したいのなら以下のように抽出します。

titile = ex[title]

リストの中の"無料で簡単に使える"を抽出する場合は以下です

coment = ex[feature][0] #リストの一番初めは0からあ始まります。

次に辞書の中身を取り出したい場合は以下です

url = ex[action][url]

以上です。

終わりに

今回はAPIとJSONについてやりました。どちらも大切なのでしっかり勉強しましょう。じ

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?