Skip to main content

Overview

FastrAPI provides constants for HTTP and WebSocket status codes, making your code more readable and maintainable. Import them from fastrapi.status.
from fastrapi import FastrAPI
from fastrapi.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND

app = FastrAPI()

@app.post("/users", status_code=HTTP_201_CREATED)
def create_user():
    return {"id": 1, "name": "John"}

HTTP status codes

1xx Informational

HTTP_100_CONTINUE
int
default:"100"
The server has received the request headers and the client should proceed to send the request body
HTTP_101_SWITCHING_PROTOCOLS
int
default:"101"
The server is switching protocols as requested by the client
HTTP_102_PROCESSING
int
default:"102"
The server has received and is processing the request, but no response is available yet
HTTP_103_EARLY_HINTS
int
default:"103"
Used to return some response headers before final HTTP message

2xx Success

HTTP_200_OK
int
default:"200"
The request succeeded
HTTP_201_CREATED
int
default:"201"
The request succeeded and a new resource was created
HTTP_202_ACCEPTED
int
default:"202"
The request has been accepted for processing, but processing is not complete
HTTP_203_NON_AUTHORITATIVE_INFORMATION
int
default:"203"
The request was successful but the enclosed payload has been modified by a transforming proxy
HTTP_204_NO_CONTENT
int
default:"204"
The request succeeded but there is no content to send
HTTP_205_RESET_CONTENT
int
default:"205"
The request succeeded and the user agent should reset the document view
HTTP_206_PARTIAL_CONTENT
int
default:"206"
The server is delivering only part of the resource due to a range header sent by the client
HTTP_207_MULTI_STATUS
int
default:"207"
Multiple status codes might be appropriate
HTTP_208_ALREADY_REPORTED
int
default:"208"
The members of a DAV binding have already been enumerated
HTTP_226_IM_USED
int
default:"226"
The server has fulfilled a request for the resource and the response is a representation of the result

3xx Redirection

HTTP_300_MULTIPLE_CHOICES
int
default:"300"
The request has more than one possible response
HTTP_301_MOVED_PERMANENTLY
int
default:"301"
The URL of the requested resource has been changed permanently
HTTP_302_FOUND
int
default:"302"
The URI of requested resource has been changed temporarily
HTTP_303_SEE_OTHER
int
default:"303"
The server sent this response to direct the client to get the requested resource at another URI
HTTP_304_NOT_MODIFIED
int
default:"304"
Used for caching purposes. The response has not been modified
HTTP_305_USE_PROXY
int
default:"305"
The requested response must be accessed by a proxy
HTTP_306_RESERVED
int
default:"306"
This response code is no longer used
HTTP_307_TEMPORARY_REDIRECT
int
default:"307"
The server sends this response to direct the client to get the requested resource at another URI with the same method
HTTP_308_PERMANENT_REDIRECT
int
default:"308"
The resource is now permanently located at another URI

4xx Client errors

HTTP_400_BAD_REQUEST
int
default:"400"
The server cannot process the request due to a client error
HTTP_401_UNAUTHORIZED
int
default:"401"
The client must authenticate itself to get the requested response
HTTP_402_PAYMENT_REQUIRED
int
default:"402"
Reserved for future use
HTTP_403_FORBIDDEN
int
default:"403"
The client does not have access rights to the content
HTTP_404_NOT_FOUND
int
default:"404"
The server cannot find the requested resource
HTTP_405_METHOD_NOT_ALLOWED
int
default:"405"
The request method is not supported for the requested resource
HTTP_406_NOT_ACCEPTABLE
int
default:"406"
The server cannot produce a response matching the list of acceptable values
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
int
default:"407"
Authentication is required to access the proxy
HTTP_408_REQUEST_TIMEOUT
int
default:"408"
The server would like to shut down this unused connection
HTTP_409_CONFLICT
int
default:"409"
The request conflicts with the current state of the server
HTTP_410_GONE
int
default:"410"
The requested content has been permanently deleted from server
HTTP_411_LENGTH_REQUIRED
int
default:"411"
The server requires the Content-Length header field
HTTP_412_PRECONDITION_FAILED
int
default:"412"
The client has indicated preconditions that the server does not meet
HTTP_413_CONTENT_TOO_LARGE
int
default:"413"
Request entity is larger than limits defined by server
HTTP_414_URI_TOO_LONG
int
default:"414"
The URI requested by the client is longer than the server is willing to interpret
HTTP_415_UNSUPPORTED_MEDIA_TYPE
int
default:"415"
The media format of the requested data is not supported by the server
HTTP_416_RANGE_NOT_SATISFIABLE
int
default:"416"
The range specified by the Range header field cannot be fulfilled
HTTP_417_EXPECTATION_FAILED
int
default:"417"
The expectation indicated by the Expect request header field cannot be met
HTTP_418_IM_A_TEAPOT
int
default:"418"
The server refuses to brew coffee because it is a teapot
HTTP_421_MISDIRECTED_REQUEST
int
default:"421"
The request was directed at a server that is not able to produce a response
HTTP_422_UNPROCESSABLE_CONTENT
int
default:"422"
The request was well-formed but contains semantic errors
HTTP_423_LOCKED
int
default:"423"
The resource that is being accessed is locked
HTTP_424_FAILED_DEPENDENCY
int
default:"424"
The request failed due to failure of a previous request
HTTP_425_TOO_EARLY
int
default:"425"
The server is unwilling to risk processing a request that might be replayed
HTTP_426_UPGRADE_REQUIRED
int
default:"426"
The server refuses to perform the request using the current protocol
HTTP_428_PRECONDITION_REQUIRED
int
default:"428"
The origin server requires the request to be conditional
HTTP_429_TOO_MANY_REQUESTS
int
default:"429"
The user has sent too many requests in a given amount of time
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
int
default:"431"
The server is unwilling to process the request because header fields are too large
The user requested a resource that is not available due to legal reasons

5xx Server errors

HTTP_500_INTERNAL_SERVER_ERROR
int
default:"500"
The server has encountered a situation it does not know how to handle
HTTP_501_NOT_IMPLEMENTED
int
default:"501"
The request method is not supported by the server
HTTP_502_BAD_GATEWAY
int
default:"502"
The server got an invalid response while working as a gateway
HTTP_503_SERVICE_UNAVAILABLE
int
default:"503"
The server is not ready to handle the request
HTTP_504_GATEWAY_TIMEOUT
int
default:"504"
The server is acting as a gateway and cannot get a response in time
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
int
default:"505"
The HTTP version used in the request is not supported by the server
HTTP_506_VARIANT_ALSO_NEGOTIATES
int
default:"506"
The server has an internal configuration error
HTTP_507_INSUFFICIENT_STORAGE
int
default:"507"
The server is unable to store the representation needed to complete the request
HTTP_508_LOOP_DETECTED
int
default:"508"
The server detected an infinite loop while processing the request
HTTP_510_NOT_EXTENDED
int
default:"510"
Further extensions to the request are required for the server to fulfill it
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
int
default:"511"
The client needs to authenticate to gain network access

WebSocket status codes

WS_1000_NORMAL_CLOSURE
int
default:"1000"
Normal closure; the connection successfully completed
WS_1001_GOING_AWAY
int
default:"1001"
The endpoint is going away (server shutdown or browser navigation)
WS_1002_PROTOCOL_ERROR
int
default:"1002"
The endpoint is terminating due to a protocol error
WS_1003_UNSUPPORTED_DATA
int
default:"1003"
The connection is being terminated because the endpoint received data of a type it cannot accept
WS_1005_NO_STATUS_RCVD
int
default:"1005"
No status code was provided even though one was expected
WS_1006_ABNORMAL_CLOSURE
int
default:"1006"
The connection was closed abnormally without sending or receiving a Close frame
WS_1007_INVALID_FRAME_PAYLOAD_DATA
int
default:"1007"
The endpoint is terminating because it received data that was inconsistent with the message type
WS_1008_POLICY_VIOLATION
int
default:"1008"
The endpoint is terminating because it received a message that violates its policy
WS_1009_MESSAGE_TOO_BIG
int
default:"1009"
The endpoint is terminating because it received a message that is too big to process
WS_1010_MANDATORY_EXT
int
default:"1010"
The client is terminating because it expected the server to negotiate one or more extensions
WS_1011_INTERNAL_ERROR
int
default:"1011"
The server is terminating because it encountered an unexpected condition
WS_1012_SERVICE_RESTART
int
default:"1012"
The server is terminating because it is restarting
WS_1013_TRY_AGAIN_LATER
int
default:"1013"
The server is terminating because it is temporarily overloaded
WS_1014_BAD_GATEWAY
int
default:"1014"
The server was acting as a gateway and received an invalid response
WS_1015_TLS_HANDSHAKE
int
default:"1015"
The connection was closed due to a failure to perform a TLS handshake

Usage examples

Setting response status codes

from fastrapi import FastrAPI
from fastrapi.status import (
    HTTP_200_OK,
    HTTP_201_CREATED,
    HTTP_204_NO_CONTENT,
    HTTP_400_BAD_REQUEST,
    HTTP_404_NOT_FOUND,
)

app = FastrAPI()

@app.post("/users", status_code=HTTP_201_CREATED)
def create_user(name: str):
    return {"id": 1, "name": name}

@app.delete("/users/{user_id}", status_code=HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
    # Delete logic here
    return None

Raising exceptions with status codes

from fastrapi import HTTPException
from fastrapi.status import HTTP_404_NOT_FOUND, HTTP_403_FORBIDDEN

@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id not in users:
        raise HTTPException(
            status_code=HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return users[user_id]

@app.delete("/admin/users/{user_id}")
def delete_user_admin(user_id: int, is_admin: bool):
    if not is_admin:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN,
            detail="Admin access required"
        )
    # Delete logic

WebSocket close codes

from fastrapi.status import WS_1000_NORMAL_CLOSURE, WS_1008_POLICY_VIOLATION

@app.websocket("/ws")
async def websocket_endpoint(ws):
    await ws.accept()
    
    try:
        data = await ws.receive_text()
        
        if is_spam(data):
            await ws.close(WS_1008_POLICY_VIOLATION)
            return
        
        # Process data...
        
        await ws.close(WS_1000_NORMAL_CLOSURE)
    except Exception:
        await ws.close(WS_1011_INTERNAL_ERROR)

RESTful API example

from fastrapi import FastrAPI, HTTPException
from fastrapi.status import (
    HTTP_200_OK,
    HTTP_201_CREATED,
    HTTP_204_NO_CONTENT,
    HTTP_404_NOT_FOUND,
    HTTP_422_UNPROCESSABLE_CONTENT,
)

app = FastrAPI()

@app.get("/items", status_code=HTTP_200_OK)
def list_items():
    return {"items": []}

@app.post("/items", status_code=HTTP_201_CREATED)
def create_item(name: str):
    if not name:
        raise HTTPException(
            status_code=HTTP_422_UNPROCESSABLE_CONTENT,
            detail="Name is required"
        )
    return {"id": 1, "name": name}

@app.get("/items/{item_id}", status_code=HTTP_200_OK)
def get_item(item_id: int):
    item = find_item(item_id)
    if not item:
        raise HTTPException(
            status_code=HTTP_404_NOT_FOUND,
            detail="Item not found"
        )
    return item

@app.delete("/items/{item_id}", status_code=HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
    deleted = remove_item(item_id)
    if not deleted:
        raise HTTPException(
            status_code=HTTP_404_NOT_FOUND,
            detail="Item not found"
        )
    return None

Build docs developers (and LLMs) love