WebAPI&HTTP基礎編

DiscordBot が使っている DiscordAPI の話

APIとHTTPの概要の解説(10分)

PythonとJavaScriptを使って色んなAPIを使ってみる(15分)

requests を使って API を使ってみる

pip install requests をしておく

import requests
from pprint import pprint

URL_API = 'https://qiita.com/api/v2'

res = requests.get(f'{URL_API}/tags')
pprint(res.json())

aiohttp を使って API を使ってみる

from discord import Intents
from discord.ext import commands
import os
import aiohttp

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or('/'),
    help_command=None,
    intents=Intents.all(),
)
token = os.environ['DISCORD_BOT_TOKEN']


@bot.command()
async def test(ctx):
    async with aiohttp.ClientSession() as session:
        async with session.get('https://qiita.com/api/v2/tags') as res:
            tags = await res.json()
            await ctx.send(tags)

bot.run(token)

実際にAPIを作って使ってみる(15分)

作る時

FastAPI 解説

  1. コード
from fastapi import FastAPI

# アプリケーションの初期化
app = FastAPI(
    title='FastAPI Heroku Template',
    description='HerokuでFastAPIによるWebAPIを作成するためのテンプレート',
    docs_url='/'
)

# /api/ に GET リクエストが送られた時の処理
@app.get('/api')
def get_sample() -> str:
    return 'sample' # 返したいデータを return する

# /api/post/ に POST リクエストが送られた時の処理
@app.post('/api/post')
def post_sample(sample: str): # 送ってほしいデータを引数に入れる
    # 変数名が JSON のキー, アノテーションされている型が欲しいデータの型
    return sample
  1. uvicorn を使うと、いい感じに動かしてくれる
    • uvicorn
      • Python のサーバーフレームワーク
      • 非同期処理に対応