Request handling and returning responses are at the heart of any development framework. This article focuses on how to handle user request parameters and responses in FastAPI.

Url path parameter

URL path parameters refer to parameters passed after the slash of the URL. For example, if we want to access project with ID 2, we can access the /project/2 URL.

But this 2, which changes every time, is called the URL path parameter.

In FastAPI, a dynamically changing URL parameter is represented with curly braces {id}, and then received as a parameter with the same id in the function.

  

@app.get('/project/{id}')

def project(id):

    return id
Copy the code

Query string parameter (Query String)

Like the path argument, you can pass the ID as a query string. The query string is passed through the URL, right? The parameter is followed by the. Such as/project /? Id =2.

In much the same way as the path argument, it is passed to the function by id. When path parameters are not found, fields are queried in the Query String.

  

# query string

@app.get('/project/')

def project(id):

    return id
Copy the code

Access to the header

Sometimes the data in the header is needed in the request, for example, the token value is often obtained in the Authorization in the request.

In this case, you can add the keyword parameter authorization=Header(None) in the view function to obtain the authorization field value of the Header through the authorization variable.

Ensure that the parameter name is the same as the field name in the header.

  

from fastapi import Header


@app.get('/project/')

def project(authorization=Header(None)):

    return authorization
Copy the code

Get the form form data

Sometimes in a request you need to retrieve data from the form, such as the username and password passed in by the user.

You can accept the username and password in the form form using username and password, respectively. The variable name is also the same as the data field passed in.

  

from fastapi import Form


@app.get('/project/')

def project(username=Form(None), password=Form(None)):

    return username
Copy the code

Access to the body

Retrieving the body is similar to retrieving the header, except that the variable retrieves all of the body data fields, instead of filling in the specified parameter names as with the header.

For example, you can receive all Body data through the item = Body(None) item variable.

Note that the Body() object in FastAPI receives JSON data. If you want to receive Form data, you need to use Form().

  

@app.post('/login/')

def project(user = Body(None)):

    return user
Copy the code

Suppose JSON data is passed in the request:

  

{

    "username": "yuz",

    "pwd": 123

}
Copy the code

The user on the interface can obtain the above data.

Additional notes on parameters

FastAPI defines an object for each parameter type:

  • Path
  • Query
  • Body
  • Form
  • File

In fact, the path argument can be obtained like this:

@app.get('/project/{id}') def project(id=Path(...) ): return idCopy the code

Get a Query string like this:

@app.get('/project/{id}') def project(id=Query(...) ): return idCopy the code

Note: Header, Query, and Path must have corresponding fields to read, but Body is used to read all fields.

Use the Request object directly

  

@app.get("/items/{item_id}")

def read_root(item_id: str, request: Request):

    client_host = request.client.host

    return {"client_host": client_host, "item_id": item_id}
Copy the code

Using the Request object to get the request object is very convenient. The only way to get data like form forms was to call request.form(),

What you get here is a coroutine object. Therefore, asynchronous processing is required:

  

async def user(req: Request):

    user = await req.form()
Copy the code

Or run with asyncio

  

def user(req: Request):

    user = asyncio.run(req.form())
Copy the code

To get the form form directly, you can also use the Form object directly.

Default return JSON

Return the dictionary or list directly

  

@app.get('/project/')

def project():

    return {"msg": "projects"}
Copy the code

Status code and response headers

  

def project():

    return JSONResponse(

        {"msg": "hello"}, 

        status_code=200, 

        headers={'you': 'ok'}

    )
Copy the code

Returns the HTML

  

def project():

    content = """

    <html>

        <h1 style="color:red">hello world</h1>

    </html>

    """

    return HTMLResponse(content)
Copy the code

Returns the file

To read files, you must first install a library aiofile.

  

pip install aiofiles
Copy the code

Then use FileResponse

  

def project():

    return FileResponse('yy.jpg')
Copy the code

Or download the file directly:

Def project(): return FileResponse(' file path.xls ', filename=' downloaded file.xls ')Copy the code

Return to the video

  

def file():

    file = open("demo.mp4", 'rb')

    return StreamingResponse(file, media_type='video/mp4')
Copy the code

But this will read the video at once, and if it is large, it will load slowly:

728 x 220 830 x 251

The best way to do this is through the generator to return the specified size of data at once:

def get_video(file): with open(file, 'rb') as f: while True: chuck = f.read(5000) if chuck: yield chuck else: Break def file(): return StreamingResponse(get_video), media_type='video/mp4')Copy the code