Reputation: 808
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?
Upvotes: 0
Views: 1508
Reputation: 6209
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.
Upvotes: 1