Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

FastAPI Requests and Responses

FastAPI Requests and Responses

In FastAPI, Request and Response are at the core of interacting with clients.

FastAPI provides powerful tools to parse request data and generate standardized responses as needed.

Next, let's take a detailed look at FastAPI requests and responses.

For HTTP-related content, you can refer to:HTTP Request Methods。

Request data

Query Parameters

In the following example, we define an /items/ route that accepts two query parameters skip and limit, both of which are integers, with default values of 0 and 10。

Example

from fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.get

(

"/items/"

)

def read_item

(

skip

:

int

=

0

,

limit

:

int

=

10

)

:

   

return

{

"skip"

:

skip

,

"limit"

:

limit

}

Run the following command in the terminal to start the application:



uvicorn main:app --reload

Now, open your browser and visit http://127.0.0.1:8000/items/, which returns the default JSON data:

Pass GET request parameters http://127.0.0.1:8000/items/?skip=1&limit=5, and the returned JSON data is shown below:

Path parameters

We can put the parameters in the path to make the URL look cleaner.

In the following example, we define a route with a path parameter item_id and a query parameter q .

Example

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.

get

(

"/items/{item_id}"

)

def

read_item

(

item_id:

int

,

q:

str

=

None

)

:

   

return

{

"item_id"

: item_id

,

"q"

: q

}

Pass GET request parameters http://127.0.0.1:8000/items/5/?q=runoob, and the returned JSON data is shown below:

Request body

Next, we create an /items/ route and use the @app.post decorator to indicate that it handles POST request.

Example

from

pydantic

import

BaseModel

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

class

Item

(

BaseModel

)

:

    name:

str

    description:

str

=

None

    price:

float

    tax:

float

=

None

@

app.

post

(

"/items/"

)

def

create_item

(

item: Item

)

:

   

return

item

A request body is defined using the Pydantic model Item, containing multiple fields, some of which have default values. For more information about Pydantic, refer to:FastAPI Pydantic Models。

Next, we can open http://127.0.0.1:8000/docs to perform a POST test:

Fill in the request parameters:

The returned result is as follows:


Response data

Return JSON data

The route handler returns a dictionary, which FastAPI automatically converts to JSON format and sends to the client as a response:

Example

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.

get

(

"/items/"

)

def

read_item

(

skip:

int

=

0

,

limit:

int

=

10

)

:

   

return

{

"skip"

: skip

,

"limit"

: limit

}

Visiting the following in the browser with the above code http://127.0.0.1:8000/items/, returns the JSON data:

Return a Pydantic model

The route handler returns a Pydantic model instance, which FastAPI automatically converts to JSON format and sends to the client as a response:

Example

from

pydantic

import

BaseModel

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

class

Item

(

BaseModel

)

:

    name:

str

    description:

str

=

None

    price:

float

    tax:

float

=

None

@

app.

post

(

"/items/"

)

def

create_item

(

item: Item

)

:

   

return

item

For a POST request, the returned data format is shown below:

{

  "name": "runoob",

  "description": "Runoob Tutorial POST 测试",

  "price": 12,

  "tax": 1

}


Headers and Cookies

Use Header and Cookie type annotations to get header and cookie data.

Example

from

fastapi

import

Header

,

Cookie

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.

get

(

"/items/"

)

def

read_item

(

user_agent:

str

=

Header

(

None

)

,

session_token:

str

=

Cookie

(

None

)

)

:

   

return

{

"User-Agent"

: user_agent

,

"Session-Token"

: session_token

}

Visiting the following in the browser with the above code http://127.0.0.1:8000/items/, returns the JSON data:


Redirects and status codes

Use RedirectResponse Implement a redirect that sends the client to the /items/ route.

Example

from

fastapi

import

Header

,

Cookie

from

fastapi

import

FastAPI

from

fastapi.

responses

import

RedirectResponse

app

=

FastAPI

(

)

@

app.

get

(

"/items/"

)

def

read_item

(

user_agent:

str

=

Header

(

None

)

,

session_token:

str

=

Cookie

(

None

)

)

:

   

return

{

"User-Agent"

: user_agent

,

"Session-Token"

: session_token

}

@

app.

get

(

"/redirect"

)

def

redirect

(

)

:

   

return

RedirectResponse

(

url

=

"/items/"

)

Visiting the following in the browser with the above code http://127.0.0.1:8000/redirect/ It will automatically jump to http://127.0.0.1:8000/items/ the page:

Use HTTPException to raise an exception, returning a custom status code and detail information.

The following example uses the shape and coords properties in an item_id is 42 will return a 404 status code:

Example

from

fastapi

import

HTTPException

app

=

FastAPI

(

)

@

app.

get

(

"/items/{item_id}"

)

def

read_item

(

item_id:

int

)

:

   

if

item_id

==

42

:

       

raise

HTTPException

(

status_code

=

404

,

detail

=

"Item not found"

)

   

return

{

"item_id"

: item_id

}

Visiting the following in the browser with the above code http://127.0.0.1:8000/items/42/ The page is shown below:


Custom response header

Use

JSONResponse

Custom response headers:

Example

from

fastapi

import

FastAPI

from

fastapi.

responses

import

JSONResponse

app

=

FastAPI

(

)

@

app.

get

(

"/items/{item_id}"

)

def

read_item

(

item_id:

int

)

:

    content

=

{

"item_id"

: item_id

}

    headers

=

{

"X-Custom-Header"

:

"custom-header-value"

}

   

return

JSONResponse

(

content

=

content

,

headers

=

headers

)

Visiting the following in the browser with the above code http://127.0.0.1:8000/items/42/ The page is shown below, where you can see our custom response headers: