Skip to main content

bareASGI-rest

This package provides enhanced support for writing REST APIs with bareASGI, (read the docs).

It includes:

  • A router to simplify the creation of REST APIs,
  • A swagger API endpoint

This is a Python 3.8+ package.

Installation

The package can be installed from pypi.

$ pip install bareASGI-rest

An ASGI server will be required to run the code. The examples below use uvicorn.

$ pip install uvicorn

Usage

The router provided by this package maps the arguments and types of request handlers.

We will create a mock book repository.

Creating typed dictionaries

Here is the type of a book. We use TypedDict to allow automatic type discovery

from datetime import datetime
from typing import TypedDict


class Book(TypedDict):
    """A Book

    Args:
        book_id (int): The book id
        title (str): The title
        author (str): The author
        published (datetime): The publication date
    """
    book_id: int
    title: str
    author: str
    published: datetime

Note: the docstring will be used to provide documentation for swagger.

Creating the API

Now we can build the API.

from datetime import datetime

from bareasgi_rest import RestError


BOOKS: dict[int, Book] = {}
NEXT_ID: int = 0

async def get_books() -> list[Book]:
    """Get all the books.

    This method gets all the books in the shop.

    Returns:
        list[Book]: All the books
    """
    return list(BOOKS.values())


async def get_book(book_id: int) -> Book:
    """Get a book for a given id

    Args:
        book_id (int): The id of the book

    Raises:
        RestError: 404, when a book is not found

    Returns:
        Book: The book
    """

    if book_id not in BOOKS:
        raise RestError(404, "Book not found")

    return BOOKS[book_id]


async def create_book(
        author: str,
        title: str,
        published: datetime
) -> int:
    """Add a book

    Args:
        author (str): The author
        title (str): The title
        published (datetime): The publication date

    Returns:
        int: The id of the new book
    """
    NEXT_ID += 1
    BOOKS[NEXT_ID] = Book(
        book_id=NEXT_ID,
        title=title,
        author=author,
        published=published
    )
    return NEXT_ID


async def update_book(
        book_id: int,
        author: str,
        title: str,
        published: datetime
) -> None:
    """Update a book

    Args:
        book_id (int): The id of the book to update
        author (str): The new author
        title (str): The title
        published (datetime): The publication date

    Raises:
        RestError: 404, when a book is not found
    """
    if book_id not in BOOKS:
        raise RestError(404, "Book not found")
    BOOKS[book_id]['title'] = title
    BOOKS[book_id]['author'] = author
    BOOKS[book_id]['published'] = published

We 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 router

Now we must create our application and add support for the router.

from bareasgi import Application
from bareasgi_rest import RestHttpRouter, add_swagger_ui


router = 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 the base_path argument can be used to prefix all paths.

The RestHttpRouter is a subclass of the basic router, so all those methods are also available.

Creating the routes

Now 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 the base_path provided to the router.

Referring back to the implementation of get_book we can see that the camel-case path variable bookId has been mapped to the snake-case book_id parameter. The JSON object provided in the body of the create_book will similarly map camel-cased properties to the snake-cased function parameters.

We can also see how the status codes have been overridden for the POST and PUT endpoints, and all the routes have the "Books" tag for grouping in the UI.

Serving the API

Finally we can serve the API:

import uvicorn

uvicorn.run(app, port=9009)

Browsing to http://localhost/api/1/swagger we should see:

Top Level

When we expand GET /books/{bookId} we can see all the information provided in the docstring and typing has been passed through to the swagger UI.

GET /books/{bookId}

Thanks

Thanks to rr- and contributors for the excellent docstring-parser package.

Metadata

Release files for bareASGI-rest 5.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bareASGI-rest 5.0.0
File Size Uploaded
bareasgi_rest-5.0.0.tar.gz 18.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for bareASGI-rest 5.0.0
File Interpreter ABI Platform
bareasgi_rest-5.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 42.8 kB

Release files / bareasgi_rest-5.0.0.tar.gz

Download URL bareasgi_rest-5.0.0.tar.gz
Size 18.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c520a54e650bc9aaa7d29de0601b428279267ad7fe5ff10d5dcf98779e287298
BLAKE2b-256 checksum
How to use checksums
ba860f592c6e541030e2cbcf2d8b5c8d96661b6a1161d0e0d461fc2fbb901a24
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / bareasgi_rest-5.0.0-py3-none-any.whl

Download URL bareasgi_rest-5.0.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
67755850659bce8e96c012de554b65dc0a280a36bd3b0b96aa6a3ed788af8611
BLAKE2b-256 checksum
How to use checksums
0a22bc095db4180e6d0b0393a97e8ccfb0a0a898aca7e785524ce911c963f56e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page