How to post JSON data from JavaScript frontend to FastAPI backend?

The way you defined ethAddress in your endpoint is expected as a query parameter; hence, the 422 Unprocessable Entity error. As per the documentation:

When you declare other function parameters that are not part of the
path parameters, they are automatically interpreted as “query”
parameters.

For the parameter to be interpreted as JSON, you need to either:

Option 1

Create a Pydantic model:

from pydantic import BaseModel

class Item(BaseModel):
    eth_addr: str

@app.post('/ethAddress')
def add_eth_addr(item: Item):
    return item

FastAPI will expect a body like:

{
    "eth_addr": "some addr"
}

Using Fetch API:

//...
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"eth_addr": "some addr"}),
//...

Option 2

or, use the Body type:

from fastapi import Body

@app.post('/ethAddress')
def add_eth_addr(eth_addr: str = Body()):
    return {'eth_addr': eth_addr}

FastAPI will expect a body like:

"some addr"

Using Fetch API:

//...
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify("some addr"),
//...

Option 3

Since you have a single body parameter, you might want to use the special Body parameter embed:

from fastapi import Body

@app.post('/ethAddress')
def add_eth_addr(eth_addr: str = Body(embed=True)):
    return {'eth_addr': eth_addr}

FastAPI will expect a body like:

{
    "eth_addr": "some addr"
}

Using Fetch API:

//...
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"eth_addr": "some addr"}),
//...

Related answers, including JavaScript examples on how to post JSON data as well, can be found here, here, as well as here and here.

Leave a Comment