Fastapi: value_error.jsondecode Invalid control character at when posting multi line text in FastAPI

Created on 1 Nov 2020  路  4Comments  路  Source: tiangolo/fastapi

hello
this is one of my endpoints which is for posting(creating) new document

@app.post("/documents", response_model=Doc, status_code=status.HTTP_201_CREATED, tags=["Web Panel"])
def create_doc(doc: DocDef , token: str = Depends(verified_admin), db: Session = Depends(get_db)):
    pass
    `print("hi")`

my schemas are:

class DocDef(BaseModel):
    name: str
    doc: str


class Doc(DocDef):
    id: int

    class Config:
        orm_mode = True

but when I want to test a multi line text document I receive an error
request body :

{
  "name": "string",
  "doc": " this is test.
this is test too."
}

response body:

{
  "detail": [
    {
      "loc": [
        "body",
        46
      ],
      "msg": "Invalid control character at: line 3 column 25 (char 46)",
      "type": "value_error.jsondecode",
      "ctx": {
        "msg": "Invalid control character at",
        "doc": "{\n  \"name\": \"string\",\n  \"doc\": \" this is test.\nthis is test too.\"\n}",
        "pos": 46,
        "lineno": 3,
        "colno": 25
      }
    }
  ]
}

please help how can I fix this
regards

Most helpful comment

Thanks again

All 4 comments

Looks very similar to #1982, as @ArcLightSlavik said

In JSON a literal line break is not allowed inside a string, it needs to be replaced by \n

So when you want to write a multiline text just go like this

```python
{
"name": "string",
"doc": " this is test.\nthis is test too."
}

Thanks for reply
So if I would like to post raw text, Is this only solution?

Yes, JSON doesn't allow breaking lines for readability.

Thanks again

Was this page helpful?
0 / 5 - 0 ratings