From e5725d2af1fd2302af83daa7e19f27e7642e3a5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 15 Dec 2018 11:36:23 +0400 Subject: [PATCH] :memo: Add docs for Form data --- docs/tutorial/form-data.md | 40 ++++++++++++++++++++++ docs/tutorial/src/form-data/tutorial001.py | 8 +++++ mkdocs.yml | 1 + 3 files changed, 49 insertions(+) create mode 100644 docs/tutorial/form-data.md create mode 100644 docs/tutorial/src/form-data/tutorial001.py diff --git a/docs/tutorial/form-data.md b/docs/tutorial/form-data.md new file mode 100644 index 000000000..dc26cf991 --- /dev/null +++ b/docs/tutorial/form-data.md @@ -0,0 +1,40 @@ +When you need to receive form data instead of JSON, you can use `Form`. + +## Import Form + +Import `Form` from `fastapi`: + +```Python hl_lines="1" +{!./tutorial/src/form-data/tutorial001.py!} +``` + +## Define Form parameters + +Create form parameters the same way you would for `Body`: + +```Python hl_lines="7" +{!./tutorial/src/form-data/tutorial001.py!} +``` + +For example, for one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` fields as form data. + +The spec requires the fields to be specifically named `username` and `password`, and to be sent as form data, not JSON. + +With `Form` you can declare the same metadata and validation as with `Body` (and `Query`, `Path`, `Cookie`). + +!!! info + `Form` is a class that inherits directly from `Body`. + +!!! info + To declare form bodies, you need to use `Form`, because otherwise the parameters would be interpreted as query parameteres or body (JSON) parameters. + +## "Form Data"? + +"Form data" is the way HTML forms (`
`) send the data to the server. + +!!! note "Technical Details" + Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. To read more about it head to the MDN web docs for POST. + +## Recap + +Use `Form` to declare form data input parameters. diff --git a/docs/tutorial/src/form-data/tutorial001.py b/docs/tutorial/src/form-data/tutorial001.py new file mode 100644 index 000000000..0290b644d --- /dev/null +++ b/docs/tutorial/src/form-data/tutorial001.py @@ -0,0 +1,8 @@ +from fastapi import FastAPI, Form + +app = FastAPI() + + +@app.post("/login/") +async def login(*, username: str = Form(...), password: str = Form(...)): + return {"username": username} diff --git a/mkdocs.yml b/mkdocs.yml index 1fc0ce5d1..0d1cabcb0 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -31,6 +31,7 @@ nav: - Header Parameters: 'tutorial/header-params.md' - Response Model: 'tutorial/response-model.md' - Extra Models: 'tutorial/extra-models.md' + - Form Data: 'tutorial/form-data.md' - Concurrency and async / await: 'async.md' - Deployment: 'deployment.md'