Debian Codegraph @

docs/examples/openapi/customize_operation_class.py

raw
1 from dataclasses import dataclass, field
2 from typing import Dict, List, Optional
3
4 from litestar import Litestar, MediaType, Request, post
5 from litestar.exceptions import HTTPException
6 from litestar.openapi.spec import OpenAPIMediaType, OpenAPIType, Operation, RequestBody, Schema
7 from litestar.status_codes import HTTP_400_BAD_REQUEST
8
9
10 @dataclass
11 class CustomOperation(Operation):
12 """Custom Operation class which includes a non-standard field which is part of an OpenAPI extension."""
13
14 x_code_samples: Optional[List[Dict[str, str]]] = field(default=None, metadata={"alias": "x-codeSamples"})
15
16 def __post_init__(self) -> None:
17 self.tags = ["ok"]
18 self.description = "Requires OK, Returns OK"
19 self.request_body = RequestBody(
20 content={
21 "text": OpenAPIMediaType(
22 schema=Schema(
23 title="Body",
24 type=OpenAPIType.STRING,
25 example="OK",
26 )
27 ),
28 },
29 description="OK is the only accepted value",
30 )
31 self.x_codeSamples = [
32 {"lang": "Python", "source": "import requests; requests.get('localhost/example')", "label": "Python"},
33 {"lang": "cURL", "source": "curl -XGET localhost/example", "label": "curl"},
34 ]
35
36
37 @post("/", operation_class=CustomOperation, media_type=MediaType.TEXT)
38 async def route(request: Request) -> str:
39 """
40
41 Returns: OK
42
43 """
44
45 if (await request.body()) == b"OK":
46 return "OK"
47 raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="request payload must be OK")
48
49
50 app = Litestar(route_handlers=[route])