Created
January 24, 2023 15:51
-
-
Save knowsuchagency/8307980a51ee2d400f4d9271dc88942f to your computer and use it in GitHub Desktop.
chalice-spec example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from apispec import APISpec | |
from chalice import Chalice, BadRequestError, Response | |
from chalice_spec import PydanticPlugin, ChalicePlugin, Docs, Operation | |
from pydantic import BaseModel, ValidationError | |
APP_NAME = "chalice-spec example" | |
app = Chalice(app_name=APP_NAME) | |
spec = APISpec( | |
chalice_app=app, | |
title=APP_NAME, | |
version="1.0.0", | |
openapi_version="3.0.2", | |
plugins=[PydanticPlugin(), ChalicePlugin()], | |
) | |
class User(BaseModel): | |
name: str | |
age: int | |
class UserRegistered(BaseModel): | |
status: str | |
user: User | |
@app.route("/") | |
def index(): | |
return {"hello": "world"} | |
@app.route( | |
"/user/register", | |
methods=["POST", "PUT"], | |
docs=Docs( | |
post=Operation( | |
request=User, | |
response=UserRegistered, | |
) | |
), | |
) | |
def register_user(): | |
body = app.current_request.json_body | |
try: | |
user = User(**body) | |
except ValidationError as e: | |
raise BadRequestError(e) | |
return UserRegistered(status="success", user=user).json() | |
@app.route("/openapi.json") | |
def openapi(): | |
return spec.to_dict() | |
@app.route("/docs") | |
def docs(): | |
html = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<meta | |
name="description" | |
content="SwaggerUI" | |
/> | |
<title>SwaggerUI</title> | |
<link rel="stylesheet" href="https://unpkg.com/[email protected]/swagger-ui.css" /> | |
</head> | |
<body> | |
<div id="swagger-ui"></div> | |
<script src="https://unpkg.com/[email protected]/swagger-ui-bundle.js" crossorigin></script> | |
<script> | |
window.onload = () => { | |
window.ui = SwaggerUIBundle({ | |
url: '/openapi.json', | |
dom_id: '#swagger-ui', | |
}); | |
}; | |
</script> | |
</body> | |
</html> | |
""" | |
return Response(body=html, status_code=200, headers={"Content-Type": "text/html"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment