This is an issue when a FastAPI endpoint is configured with status_code=204 but does not explicitly return None or use the Response class to ensure an empty body.

Why is this an issue?

The HTTP 204 (No Content) status code indicates that the server successfully processed the request but is not returning any content. According to RFC 7231, a 204 response must not contain a message body.

In FastAPI, if you define an endpoint with status_code=204 but don’t explicitly handle the response, the framework may send a small response body (typically 4 bytes containing null). This violates the HTTP specification and can cause issues with:

The problem occurs because FastAPI’s default serialization behavior attempts to serialize the return value, even when the status code indicates no content should be sent.

What is the potential impact?

This issue can lead to:

How to fix it in FastAPI

Return None explicitly from the endpoint function. This ensures FastAPI sends an empty response body.

Code examples

Noncompliant code example

from fastapi import FastAPI

app = FastAPI()

@app.delete("/resource/{id}", status_code=204)
def delete_resource(id: int):
    # Delete the resource
    ...  # Noncompliant

Compliant solution

from fastapi import FastAPI

app = FastAPI()

@app.delete("/resource/{id}", status_code=204)
def delete_resource(id: int):
    # Delete the resource
    return None

Use the Response class with status_code=204. This gives you explicit control over the response and guarantees no content is sent.

Noncompliant code example

from fastapi import FastAPI

app = FastAPI()

@app.put("/resource/{id}/archive", status_code=204)
def archive_resource(id: int):
    # Archive the resource
    ...  # Noncompliant

Compliant solution

from fastapi import FastAPI, Response

app = FastAPI()

@app.put("/resource/{id}/archive", status_code=204)
def archive_resource(id: int):
    # Archive the resource
    return Response(status_code=204)

Resources

Documentation