Package: bareasgi-rest
bareASGI-restThis package provides enhanced support for writing REST
APIs withbareASGI,
(read thedocs).It includes:A router to simplify the creation of REST APIs,A swagger API endpointThis is a Python 3.8+ package.InstallationThe package can be installed from pypi.$pipinstallbareASGI-restAn ASGI server will be required to run the code. The examples below useuvicorn.$pipinstalluvicornUsageThe router provided by this package maps the arguments and
types of request handlers.We will create a mock book repository.Creating typed dictionariesHere is the type of a book. We useTypedDictto allow automatic type discoveryfromdatetimeimportdatetimefromtypingimportTypedDictclassBook(TypedDict):"""A BookArgs:book_id (int): The book idtitle (str): The titleauthor (str): The authorpublished (datetime): The publication date"""book_id:inttitle:strauthor:strpublished:datetimeNote: the docstring will be used to provide documentation for swagger.Creating the APINow we can build the API.fromtypingimportDict,Listfrombareasgi_restimportRestErrorBOOKS:Dict[int,Book]={}NEXT_ID:int=0asyncdefget_books()->List[Book]:"""Get all the books.This method gets all the books in the shop.Returns:List[Book]: All the books"""returnlist(BOOKS.values())asyncdefget_book(book_id:int)->Book:"""Get a book for a given idArgs:book_id (int): The id of the bookRaises:RestError: 404, when a book is not foundReturns:Book: The book"""ifbook_idnotinBOOKS:raiseRestError(404,"Book not found")returnBOOKS[book_id]asyncdefcreate_book(author:str,title:str,published:datetime)->int:"""Add a bookArgs:author (str): The authortitle (str): The titlepublished (datetime): The publication dateReturns:int: The id of the new book"""NEXT_ID+=1BOOKS[NEXT_ID]=Book(book_id=NEXT_ID,title=title,author=author,published=published)returnNEXT_IDasyncdefupdate_book(book_id:int,author:str,title:str,published:datetime)->None:"""Update a bookArgs:book_id (int): The id of the book to updateauthor (str): The new authortitle (str): The titlepublished (datetime): The publication dateRaises:RestError: 404, when a book is not found"""ifbook_idnotinBOOKS:raiseRestError(404,"Book not found")BOOKS[book_id]['title']=titleBOOKS[book_id]['author']=authorBOOKS[book_id]['published']=publishedWe can see that errors are handler by raising ResetError.
A convention has been applied such that the status code MUST
appear before the message, separated by a comma.Adding support for the REST routerNow we must create our application and add support for the router.frombareasgiimportApplicationfrombareasgi_restimportRestHttpRouter,add_swagger_uirouter=RestHttpRouter(None,title="Books",version="1",description="A book api",base_path='/api/1',tags=[{'name':'Books','description':'The book store API'}])app=Application(http_router=router)add_swagger_ui(app)Note thebase_pathargument can be used to prefix all
paths.TheRestHttpRouteris a subclass of the basic router, so
all those methods are also available.Creating the routesNow we can create the routes:tags=['Books']router.add_rest({'GET'},'/books',get_books,tags=tags)router.add_rest({'GET'},'/books/{bookId:int}',get_book,tags=tags)router.add_rest({'POST'},'/books',create_book,tags=tags,status_code=201)router.add_rest({'PUT'},'/books/{bookId:int}',update_book,tags=tags,status_code=204)First we should note that the paths will be prefixed with thebase_pathprovided to the router.Referring back to the implementation ofget_bookwe can
see that the camel-case path variablebookIdhas been
mapped to the snake-casebook_idparameter. The JSON object provided in the body of thecreate_bookwill
similarly map camel-cased properties to the snake-cased
function parameters.We can also see how the status codes have been overridden
for thePOSTandPUTendpoints, and all the routes
have the "Books" tag for grouping in the UI.Serving the APIFinally we can serve the API:importuvicornuvicorn.run(app,port=9009)Browsing tohttp://localhost/api/1/swaggerwe should see:When we expandGET /books/{bookId}we can see all the
information provided in the docstring and typing has been
passed through to the swagger UI.ThanksThanks torr-and contributors
for the excellentdocstring-parserpackage.