0
1

More than 1 year has passed since last update.

FastAPIで作るWebアプリ - Form validation

Last updated at Posted at 2021-10-31

今回はFastAPIのFormのValidationについてです。

【過去記事】
Python Asyncio入門
Aiohttpで作るSimple Web Server - Qiita
Starletteで作る Simple Web Server - QIita
FastAPIで作るWebアプリ - 基本
FastAPIで作るWebアプリ - validation
FastAPIで作るWebアプリ - Body validation
FastAPIで作るWebアプリ - Form validation

FastAPI 公式サイト

Bodyの時とほぼ同じプログラムです。

form1.py
from fastapi import Form, FastAPI

app = FastAPI()

@app.post("/items/")
async def create_item(name: str=Form(...), price: float=Form(...)):
    return {"name": name, "price": price}

Form()関数はBody()関数とほぼ同じですが、以下の違いを吸収します。

  • Body Request => Content-Type: application/json
  • Form Data => Content-Type: application/x-www-form-urlencoded

正常なデータをRequestします。

curl -X 'POST' 'http://localhost:8000/items/' -H 'accept: application/json' -H 'Content-Type: application/x-www-form-urlencoded' -d 'name=Hanako&price=5.3'

サーバ側は200 okの出力をし、クライアント側は以下のデータを受け取ります。

{"name":"Hanako","price":5.3}

もちろんエラーデータのRequestに対しては、Bodyの時と同じようにエラーとなります。

今回は以上です。

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