AsyncIO REST example with aiohttp, motor and umongo

Not so long I started to use aiohttp to create small services, they are 2-5x times faster.
Here is my example of such an application with CRUD operations for items stored in MongoDB: https://github.com/sneawo/asyncio-rest-example. It’s not production-ready, but there is an example of how to run it with docker-compose.

  • Makefile - the different commands to install, test and run the application, make help to list them.
  • Dockerfile, docker-compose.yml - an example of how to run the application in docker environment, also it’s used to run MongoDB in local.
  • app/__init__.py - set up logging with python-json-logger
  • app/config.py - the configs.
  • app/db.py - setup the connection to MongoDB and initialize an instance for umongo documents.
  • app/main.py - initialize aiohttp application.
  • app/models.py - the description of umongo models.
  • app/schemas.py - the validation and response schemas.
  • app/services.py - the operations on items, I separated them from views, this way they can be more easily reused and tested.
  • app/views.py - REST endpoints.

To test it with HTTPie.

Create http POST http://localhost:8080/items name=test

HTTP/1.1 201 Created

{
    "created_time": "2019-08-15T11:09:56.908000+00:00",
    "id": "5d553d841be1ebe805280c1d",
    "name": "test"
}

List http http://localhost:8080/items

HTTP/1.1 200 OK

[
    {
        "created_time": "2019-08-15T11:09:56.908000+00:00",
        "id": "5d553d841be1ebe805280c1d",
        "name": "test"
    }
]

Get http http://localhost:8080/items/5d553d841be1ebe805280c1d

HTTP/1.1 200 OK

{
    "created_time": "2019-08-15T11:09:56.908000+00:00",
    "id": "5d553d841be1ebe805280c1d",
    "name": "test"
}

Update http PUT http://localhost:8080/items/5d553d841be1ebe805280c1d name=test1

HTTP/1.1 200 OK

{
    "created_time": "2019-08-15T11:09:56.908000+00:00",
    "id": "5d553d841be1ebe805280c1d",
    "name": "test1",
    "updated_time": "2019-08-15T11:15:05.959000+00:00"
}

Delete http DELETE http://localhost:8080/items/5d553d841be1ebe805280c1d

HTTP/1.1 204 No Content
comments powered by Disqus