【FastAPI】Cookieの保存・取得方法について
当ページのリンクには広告が含まれています。

Cookieは、ブラウザに任意の情報を保存するために用いられ
- string
- list
- dict
などのデータを保存することが出来ます。
今回はFastAPI
でCookie
の情報を保存・取得する方法についてご紹介いたします。
あわせて読みたい


Response Cookies – FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
あわせて読みたい


クッキーのパラメータ – FastAPI
FastAPI framework, high performance, easy to learn, fast to code, ready for production
FastAPIの基礎についての記事まとめ
目次
Cookieの保存 – set_cookie
cookie
の保存は、Response
クラスのset_cookie
を使用します。
https://fastapi.tiangolo.com/ja/advanced/response-cookies/
response.set_cookie(key="sample_cookie", value="sample_cookie_value")
key
とvalue
をそれぞれ設定します。
from fastapi import Response
~~~
@app.get('/cookie')
def save_cookie(response: Response):
response.set_cookie(key="sample_cookie", value="sample_cookie_value")
return "ok"
関連記事


【FastAPI】リクエスト・レスポンスヘッダーを追加【header】
FastAPIでのheaderのパラメーターの受け取り方をご紹介いたします。 headerの操作は、JWTやtoken認証などで用いられる必須の機能です。 今回は、ヘッダーのリクエスト・…
ドキュメントを確認してみましょう。API
を実行し

ブラウザの開発者ツールでcookie
を確認します。
Google chrome
の場合はF12
を押し、Application
、左のサイドバーからCookie
を選択します。

ちゃんと保存されていますね!
Cookieの取得
Cookie
を受け取るには、下記の様に記載します。
https://fastapi.tiangolo.com/ja/tutorial/cookie-params/
sample_cookie: Optional[str] = Cookie(None)
Cookie
を設定しない場合、クエリパラメータとして受け取られてしまうので注意が必要です。
from fastapi import Cookie
~~~
@app.get('/cookie2')
def get_cookie(sample_cookie: Optional[str] = Cookie(None)):
return {
"sample_cookie": sample_cookie
}
先程保存したcookie
を取得する関数を作成しました。見ていきましょう。

sample_cookie_value
と値が取得できています!これでCookie
も自由自在ですね!
FastAPIの基礎についての記事まとめ
コメント