HTTP Status Codes

In MVI, when an API entrypoint function gets to a return statement, the default behaviour is to respond with a status code of 200. But sometimes it might be desireable to respond with some other status code. Let’s look at an example with a dictionary for storing some data:

import logging

from mvi import service
from mvi.exceptions import HTTPException

logger = logging.getLogger(__name__)

STORAGE_DICTS = dict()

@service.entrypoint(status_code=201)
def create_new_dict(dict_name: str, content: dict):

    if STORAGE_DICTS.get(dict_name, False):
        raise HTTPException(status_code=409, detail=f"{dict_name} already exists")

    STORAGE_DICTS[dict_name] = content
    return "Created"


@service.entrypoint()
def get_dict(dict_name: str):
    return STORAGE_DICTS[dict_name]


if __name__ == "__main__":
    service.run()

For create_new_dict() in this example, we have changed the status code of a successful request to be 201 Created instead of 200 OK. If we try to create a new dictionary when it already exists we raise an HTTPException, which makes the entrypoint respond with that status code and the detail in the response body.

Note

Here is a full list of HTTP status codes