I have a FastAPI app that implements a route like so.
from fastapi import FastAPI
api = FastAPI()
@api.post("/myroute/")
def myroute(a: str, b: str) -> str:
return f"a={a}, b={b}"
This works as expected when I run the server and use Swagger to interact with it.
I have the following unit test.
from fastapi.testclient import TestClient
def test_myroute():
client = TestClient(api)
response = client.post("/myroute/", json={"a": "dog", "b": "cat"})
assert response.status_code == 200
The unit test fails with an HTTP 422 Unprocessable Entity.
Have I written the unit test incorrectly?
There is a similar StackOverflow question here, but there the solution is to use the json
keyword in the unit test, which I am already doing.
CodePudding user response:
Here is a solution.
from fastapi import FastAPI
from pydantic import BaseModel
api = FastAPI()
class Arguments(BaseModel):
a: str
b: str
@api.post("/myroute/")
def myroute(arguments: Arguments) -> str:
return f"a={arguments.a}, b={arguments.b}":
See the comment responding to the original post for an explanation.