12

I try to test an endpoint with the TestClient from FastAPI (which is the Scarlett TestClient basically).

The response code is always 422 Unprocessable Entity.

This is my current Code:

from typing import Dict, Optional

from fastapi import APIRouter
from pydantic import BaseModel

router = APIRouter()


class CreateRequest(BaseModel):
    number: int
    ttl: Optional[float] = None


@router.post("/create")
async def create_users(body: CreateRequest) -> Dict:
    return {
        "msg": f"{body.number} Users are created"
    }

As you can see I'm also passing the application/json header to the client to avoid a potential error.

And this is my Test:

from fastapi.testclient import TestClient
from metusa import app


def test_create_50_users():
    client = TestClient(app)
    client.headers["Content-Type"] = "application/json"

    body = {
        "number": 50,
        "ttl": 2.0
    }
    response = client.post('/v1/users/create', data=body)

    assert response.status_code == 200
    assert response.json() == {"msg": "50 Users created"}

I also found this error message in the Response Object

b'{"detail":[{"loc":["body",0],"msg":"Expecting value: line 1 column 1 (char 0)","type":"value_error.jsondecode","ctx":{"msg":"Expecting value","doc":"number=50&ttl=2.0","pos":0,"lineno":1,"colno":1}}]}'

Thank you for your support and time!

1 Answer 1

8

You don't need to set headers manualy. You can use json argument insteed of data in client.post method.

def test_create_50_users():
    client = TestClient(router)

    body = {
        "number": 50,
        "ttl": 2.0
    }
    response = client.post('/create', json=body)

If you still want to use data attribute, you need to use json.dumps

def test_create_50_users():
    client = TestClient(router)
    client.headers["Content-Type"] = "application/json"

    body = {
        "number": 50,
        "ttl": 2.0
    }
    response = client.post('/create', data=json.dumps(body))
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, the data=json.dumps(body) was key to fixing my issue. I used data=body and received the Unprocessable Entity error, too.
idk, both don't work for me
ok, my fault. The answer is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.