Send JSON from curl by POST to Python FastAPI

Question:

I’m running following script:

from fastapi import FastAPI
from fastapi import Request
import os
import uvicorn

app = FastAPI()

@app.post("/")
async def root(data: Request):
    try:
        res = await data.json()
    except Exception as ex:
        res = str(ex)
    return res


if __name__ == "__main__":
    prog = os.path.basename(__file__).replace(".py","")
    uvicorn.run("%s:app" % prog, host="127.0.0.1", port=5000, log_level="debug",reload=True)  

and try to test it by:

curl -d '{"text":"Foo Bar"}' -H "Content-Type: application/json" -X POST http://localhost:5000

What I get is always:

"Expecting value: line 1 column 1 (char 0)"

What’s wrong here?

Windows 11, Python 3.9.9

Asked By: Michael Hecht

||

Answers:

On Windows, using single quotes around data (and in general) would not work, and you would thus need to escape double quotes. For example (adjust the port number as required):

curl -X "POST" 
  "http://127.0.0.1:8000/" 
  -H "accept: application/json" 
  -H "Content-Type: application/json" 
  -d "{"foo": "bar"}"
     ^ ^^   ^^  ^^   ^^ ^

The above in a single line:

curl -X "POST" "http://127.0.0.1:8000/" -H "accept: application/json" -H "Content-Type: application/json" -d "{"foo": "bar"}"

Note that you can also use the interactive API documentation, provided by Swagger UI at /docs, which allows you to test your API directly from the browser, as well as provides you with cURL command, after submitting the data, which you can copy and test it on your own. For Swagger UI to provide you with the request body area (where you can type the data you would like to send), you need to define a body parameter in your endpoint. Since you seem to be sending arbitrary JSON data, you can use the following (please have a look at this answer and this answer for more details on how to send JSON data to a FastAPI backend). Example:

from typing import Dict, Any

@app.post('/')
def main(payload: Dict[Any, Any]):
    return payload
Answered By: Chris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.