question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to pass raw text in requests body

See original GitHub issue

Reproduce

I want to pass raw text to request body. But it has “422 Error: Unprocessable Entity” due to the \n

from posixpath import join

from fastapi import FastAPI
from pydantic import BaseModel


class Text2kgParams(BaseModel):
    host: str
    dataset: str
    text: str


app = FastAPI()


@app.post("/text2kg")
async def contract(params: Text2kgParams):
    endpoint = join(params.host, params.dataset)
    return {"endpoint": endpoint, "text": params.text}

Description

If there is text contains \n, it will throw the 422 error.

image

image

Environment

  • OS: macOS
  • FastAPI Version : 0.6.1
  • Python: 3.7.6

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:7
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
ycdcommented, Nov 26, 2020

Hmm, well you can create a workaround for it, here is one for inspiration

from fastapi import FastAPI, Body, APIRouter, Request, Response
from typing import Callable
from fastapi.routing import APIRoute
from pydantic import BaseModel
import json
from ast import literal_eval


class CustomRoute(APIRoute):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            request_body = await request.body()

            request_body = literal_eval(request_body.decode("utf-8"))

            request_body = json.dumps(request_body).encode("utf-8")

            request._body = request_body  # Note that we are overriding the incoming request's body

            response = await original_route_handler(request)
            return response

        return custom_route_handler


app = FastAPI()
router = APIRouter(route_class=CustomRoute)


class TestModel(BaseModel):
    name: str


@router.post("/")
async def dummy(model: TestModel = Body(...)):
    return model


app.include_router(router)

This is actually an invalid body

curl -X POST "http://127.0.0.1:8000/"  -d "{  \"name\": \"st""ring\"}" 

But with a custom route, we can make it work

Out: {"name":"string"}
3reactions
ycdcommented, Nov 26, 2020

Of course, it would fail, you can not use double quotes with the string that you created with double-quotes.

See, even syntax highlighting understands there is an error.

{
"text" : "This is a "sample" text"
}
  • What you can do?

You can use an escape character \

{
"text" : "This is a \"sample\" text"
}

Or you can use single quotes instead of double quotes

{
"text" : "This is a 'sample' text"
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to send raw data in a POST request Python
You are still able to use raw json data for requests by just passing in json=raw_data, raw data being a string. This is...
Read more >
Raw request body - HTTPie 3.2.1 (latest) docs
There are three methods for passing raw request data: piping via stdin , --raw='data' , and @/file/path . Redirected Input. The universal method...
Read more >
How do I post request body with Curl? - ReqBin
To send data to the server in the POST request body, you must pass the required data to Curl using the -d or...
Read more >
Accepting Raw Request Body Content in ASP.NET Core API ...
Lets start with a non-raw request, but rather with posting a string as JSON since that is very common. You can accept a...
Read more >
Add a Request Body to a POST Request | API Connector
Use Cell Values in Request Bodies ... You can reference cells in the request body by wrapping your cell reference in 3 plus...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found