]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
✨ Add support for Python's http.HTTPStatus in status_code (#1534)
authorretnikt <master@retnikt.uk>
Sat, 13 Jun 2020 17:40:10 +0000 (18:40 +0100)
committerGitHub <noreply@github.com>
Sat, 13 Jun 2020 17:40:10 +0000 (19:40 +0200)
* Normalise IntEnums to ints for route status codes

Closes #1349

* add tests for status code enum support

* add docs for status code enum support

* add endpoint test for enum status code

* 📝 Update note about http.HTTPStatus

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
docs/en/docs/tutorial/response-status-code.md
fastapi/routing.py
tests/main.py
tests/test_application.py

index 05244edf64c69f13e5625c2eada9b5407afe2502..7915624fa67eeaa2c98a9bce2f63b8230ac1c1ca 100644 (file)
@@ -17,6 +17,9 @@ The same way you can specify a response model, you can also declare the HTTP sta
 
 The `status_code` parameter receives a number with the HTTP status code.
 
+!!! info
+    `status_code` can alternatively also receive an `IntEnum`, such as Python's <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>.
+
 It will:
 
 * Return that status code in the response.
index 16eb7ab0b4a3b64db58a493db764198f4f8b613a..38216823ac067836e1dd3aa0dc4bcbd6fa14ecc9 100644 (file)
@@ -1,4 +1,5 @@
 import asyncio
+import enum
 import inspect
 import json
 from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union
@@ -296,6 +297,9 @@ class APIRoute(routing.Route):
         dependency_overrides_provider: Any = None,
         callbacks: Optional[List["APIRoute"]] = None,
     ) -> None:
+        # normalise enums e.g. http.HTTPStatus
+        if isinstance(status_code, enum.IntEnum):
+            status_code = int(status_code)
         self.path = path
         self.endpoint = endpoint
         self.name = get_name(endpoint) if name is None else name
index ab0b186072933eb2bb4c770b4e78183c7b4d3b29..f32856cb6c3a27dafc3780a5f3c853ff28d248c7 100644 (file)
@@ -1,3 +1,5 @@
+import http
+
 from fastapi import FastAPI, Path, Query
 
 app = FastAPI()
@@ -184,3 +186,8 @@ def get_query_param_required(query=Query(...)):
 @app.get("/query/param-required/int")
 def get_query_param_required_type(query: int = Query(...)):
     return f"foo bar {query}"
+
+
+@app.get("/enum-status-code", status_code=http.HTTPStatus.CREATED)
+def get_enum_status_code():
+    return "foo bar"
index f6d77460a4032c625b7e6361868431b7e8f5fd9c..fcb77c93e536461ae63134e84123f484bceddc19 100644 (file)
@@ -1078,6 +1078,18 @@ openapi_schema = {
                 ],
             }
         },
+        "/enum-status-code": {
+            "get": {
+                "responses": {
+                    "201": {
+                        "description": "Successful Response",
+                        "content": {"application/json": {"schema": {}}},
+                    },
+                },
+                "summary": "Get Enum Status Code",
+                "operationId": "get_enum_status_code_enum_status_code_get",
+            }
+        },
     },
     "components": {
         "schemas": {
@@ -1149,3 +1161,9 @@ def test_redoc():
     assert response.status_code == 200, response.text
     assert response.headers["content-type"] == "text/html; charset=utf-8"
     assert "redoc@next" in response.text
+
+
+def test_enum_status_code_response():
+    response = client.get("/enum-status-code")
+    assert response.status_code == 201, response.text
+    assert response.json() == "foo bar"