1

I am trying to pass some json contents from the client to the server via some simple REST API built with FastAPI (using uvicorn). If I wrap the file contents into a pydantic.BaseModel like so

app = FastAPI()

class ConfigContents(BaseModel):
    str_contents: str

@app.post("/writeFile/{fn}")
async def write_file(fn: str, contents: ConfigContents):
    filepath = "/some_server_dir/" + fn
    with open(filepath, "w") as f:
        f.write(contents.str_contents)
    return contents

I essentially get what I want, i.e. on the client side (using the request-library), I can execute

response = requests.post("http://127.0.0.1:8000/writeFile/my_file.json", 
             data=json.dumps({"str_contents": contents}))

and end up with the file contents assigned to response and written to the file on the "server". My question is: is there a simpler way to achieve the same, e.g. just passing the json contents as a string to the server without the need to wrap it into a model?

1
  • 1
    The fact that you are wrapping it into a model is a feature of Fastapi. It ensures for you that the data passed in input is correct (syntactally speaking). You can sure remove it, and access the content, but you'll have to handle it on your own. See fastapi.tiangolo.com/tutorial/body-multiple-params/… in particular the Body(...) parameter Commented Jan 11, 2021 at 8:39

1 Answer 1

2

from the fastApi doc:

If you don't want to use Pydantic models, you can also use Body parameters. See the docs for Body - Multiple Parameters: Singular values in body.

The doc for Body explains that you can declare any parameter with a Body(...) default value to make it a value to be retrieved from the resquest body.

This means you could simply delete your pydantic model and change your write_file function declaration to:

async def write_file(fn: str, contents=Body(...)):
   ...

However, it would be a (very) bad idea in my opinion. FastApi uses the pydantic models to validate the provided data and to generate convenient API doc. I would rather recommand to improve and develop the pydantic models you use to get better automatic validation and documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

Your advice re models sounds very reasonable, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.