Process body as plain text in FastAPI and show in SwaggerUI

Viewed 17

I am trying to have my FastAPI accept a string as body. Note that this string is not a JSON. For me it is important that the body argument can also be specified in the SwaggerUI that FastAPI provides. At the moment, I am doing the following:

@app.put("items/{item_name}")
async def put(item_name: str, body: str = Body(..., media_type="text/plain")):
   print(body)

But it gives me an error: Error: Unprocessable Entity

1 Answers

I hope it fixes:

Create your pydantic model:

from pydantic import BaseModel
class Item(BaseModel):
     item_name: str
     body: str

(if you create it in same page):

@app.put("items/{item_name}")
async def put(item_name: Item.item_name, body: Item.body):
   return body

Also it is better to use "id"s to update something.

Related