# Build a Cocktail API with Beanie and MongoDB

I have a MongoDB collection containing cocktail recipes that I've made during lockdown.

Recently, I've been trying to build an API over it, using some technologies I know well. I wasn't very happy with the results. Writing code to transform the BSON that comes out of MongoDB into suitable JSON is relatively fiddly. I felt I wanted something more declarative, but my most recent attempt—a mash-up of Flask, MongoEngine, and Marshmallow—just felt clunky and repetitive. I was about to start experimenting with building my own declarative framework, and then I stumbled upon an introduction to a brand new MongoDB ODM called Beanie. It looked like exactly what I was looking for.

The code used in this post borrows heavily from the Beanie post linked above. I've customized it to my needs, and added an extra endpoint that makes use of MongoDB Atlas Search, to provide autocompletion, for a GUI I'm planning to build in the future.

You can find all the code on GitHub.

>
>
>**Note**: The code here was written for Beanie 0.2.3. It's a new library, and things are moving fast! Check out the Beanie Changelog to see what things have changed between this version and the latest version of Beanie.
>
>

I have a collection of documents that looks a bit like this:

``` json
{
   "_id": "5f7daa158ec9dfb536781b0a",
   "name": "Hunter's Moon",
   "ingredients": 
      {
         "name": "Vermouth",
         "quantity": {
            "quantity": "25",
            "unit": "ml"
         }
      },
      {
         "name": "Maraschino Cherry",
         "quantity": {
            "quantity": "15",
            "unit": "ml"
         }
      },
      {
         "name": "Sugar Syrup",
         "quantity": {
            "quantity": "10",
            "unit": "ml"
         }
      },
      {
         "name": "Lemonade",
         "quantity": {
            "quantity": "100",
            "unit": "ml"
         }
      },
      {
         "name": "Blackberries",
         "quantity": {
            "quantity": "2",
            "unit": null
         }
      }
   ]
}
```

The promise of Beanie and FastAPI—to just build a model for this data and have it automatically translate the tricky field types, like `ObjectId` and `Date` between BSON and JSON representation—was very appealing, so I fired up a new Python project, and defined my schema in a [models submodule like so:

``` python
class Cocktail(Document):
   class DocumentMeta:
      collection_name = "recipes"

   name: str
   ingredients: List"Ingredient"]
   instructions: List[str]

class Ingredient(BaseModel):
   name: str
   quantity: Optional["IngredientQuantity"]

class IngredientQuantity(BaseModel):
   quantity: Optional[str]
   unit: Optional[str]

Cocktail.update_forward_refs()
Ingredient.update_forward_refs()
```

I was pleased to see that I could define a `DocumentMeta` inner class and override the collection name. It was a feature that I thought *should* be there, but wasn't totally sure it would be.

The other thing that was a little bit tricky was to get `Cocktail` to refer to `Ingredient`, which hasn't been defined at that point. Fortunately,
[Pydantic's `update_forward_refs` method can be used later to glue together the references. I could have just re-ordered the class definitions, but I preferred this approach.

The beaniecocktails package, defined in the `__init__.py` file, contains mostly boilerplate code for initializing FastAPI, Motor, and Beanie:

``` python
# ... some code skipped

@app.on_event("startup")
async def app_init():
   client = motor.motor_asyncio.AsyncIOMotorClient(Settings().mongodb_url)
   init_beanie(client.get_default_database(), document_models=Cocktail])
   app.include_router(cocktail_router, prefix="/v1")
```

The code above defines an event handler for the FastAPI app startup. It connects to MongoDB, configures Beanie with the database connection, and provides the `Cocktail` model I'll be using to Beanie.

The last line adds the `cocktail_router` to Beanie. It's an `APIRouter` that's defined in the [routes submodule.

So now it's time to show you the routes file—this is where I spent most of my time. I was *amazed* by how quickly I could get API endpoints developed.

``` python
# ... imports skipped

cocktail_router = APIRouter()
```

The `cocktail_router` is responsible for routing URL paths to different function handlers which will provide data to be rendered as JSON. The simplest handler is probably:

``` python
@cocktail_router.get("/cocktails/", response_model=ListCocktail])
async def list_cocktails():
   return await Cocktail.find_all().to_list()
```

This handler takes full advantage of these facts: FastAPI will automatically render Pydantic instances as JSON; and Beanie `Document` models are defined using Pydantic. `Cocktail.find_all()` returns an iterator over all the `Cocktail` documents in the `recipes` collection. FastAPI can't deal with these iterators directly, so the sequence is converted to a list using the `to_list()` method.

If you have the [Just task runner installed, you can run the server with:

``` bash
just run
```

If not, you can run it directly by running:

``` bash
uvicorn beaniecocktails:app --reload --debug
```

And then you can test the endpoint by pointing your browser at
"".

A similar endpoint for just a single cocktail is neatly encapsulated by two methods: one to look up a document by `_id` and raise a "404 Not Found" error if it doesn't exist, and a handler to route the HTTP request. The two are neatly glued together using the `Depends` declaration that converts the provided `cocktail_id` into a loaded `Cocktail` instance.

``` python
async def get_cocktail(cocktail_id: PydanticObjectId) -> Cocktail:
   """ Helper function to look up a cocktail by id """

   cocktail = await Cocktail.get(cocktail_id)
   if cocktail is None:
      raise HTTPException(status_code=404, detail="Cocktail not found")
   return cocktail

@cocktail_router.get("/cocktails/{cocktail_id}", response_model=Cocktail)
async def get_cocktail_by_id(cocktail: Cocktail = Depends(get_cocktail)):
   return cocktail
```

*Now* for the thing that I really like about Beanie: its integration with MongoDB's Aggregation Framework. Aggregation pipelines can reshape documents through projection or grouping, and Beanie allows the resulting documents to be mapped to a Pydantic `BaseModel` subclass.

Using this technique, an endpoint can be added that provides an index of all of the ingredients and the number of cocktails each appears in:

``` python
# models.py:

class IngredientAggregation(BaseModel):
   """ A model for an ingredient count. """

   id: str = Field(None, alias="_id")
   total: int

# routes.py:

@cocktail_router.get("/ingredients", response_model=ListIngredientAggregation])
async def list_ingredients():
   """ Group on each ingredient name and return a list of `IngredientAggregation`s. """

   return await Cocktail.aggregate(
      aggregation_query=[
         {"$unwind": "$ingredients"},
         {"$group": {"_id": "$ingredients.name", "total": {"$sum": 1}}},
         {"$sort": {"_id": 1}},
      ],
      item_model=IngredientAggregation,
   ).to_list()
```

The results, at "", look a bit like this:

``` json
[
   {"_id":"7-Up","total":1},
   {"_id":"Amaretto","total":2},
   {"_id":"Angostura Bitters","total":1},
   {"_id":"Apple schnapps","total":1},
   {"_id":"Applejack","total":1},
   {"_id":"Apricot brandy","total":1},
   {"_id":"Bailey","total":1},
   {"_id":"Baileys irish cream","total":1},
   {"_id":"Bitters","total":3},
   {"_id":"Blackberries","total":1},
   {"_id":"Blended whiskey","total":1},
   {"_id":"Bourbon","total":1},
   {"_id":"Bourbon Whiskey","total":1},
   {"_id":"Brandy","total":7},
   {"_id":"Butterscotch schnapps","total":1},
]
```

I loved this feature so much, I decided to use it along with [MongoDB Atlas Search, which provides free text search over MongoDB collections, to implement an autocomplete endpoint.

The first step was to add a search index on the `recipes` collection, in the MongoDB Atlas web interface:

I had to add the `name` field as an "autocomplete" field type.

I waited for the index to finish building, which didn't take very long, because it's not a very big collection. Then I was ready to write my autocomplete endpoint:

``` python
@cocktail_router.get("/cocktail_autocomplete", response_model=Liststr])
async def cocktail_autocomplete(fragment: str):
   """ Return an array of cocktail names matched from a string fragment. """

   return [
      c["name"]
      for c in await Cocktail.aggregate(
         aggregation_query=[
            {
               "$search": {
                  "autocomplete": {
                     "query": fragment,
                     "path": "name",
                  }
               }
            }
         ]
      ).to_list()
   ]
```

The `$search` aggregation stage specifically uses a search index. In this case, I'm using the `autocomplete` type, to match the type of the index I created on the `name` field. Because I wanted the response to be as lightweight as possible, I'm taking over the serialization to JSON myself, extracting the name from each `Cocktail` instance and just returning a list of strings.

The results are great!

Pointing my browser at
"" gives me `["Imperial Fizz","Vodka Fizz"]`, and
"" gives me `["Manhattan","Espresso Martini"]`.

The next step is to build myself a React front end, so that I can truly call this a [FARM Stack app.

## Wrap-Up

I was really impressed with how quickly I could get all of this up and running. Handling of `ObjectId` instances was totally invisible, thanks to Beanie's `PydanticObjectId` type, and I've seen other sample code that shows how BSON `Date` values are equally well-handled.

I need to see how I can build some HATEOAS functionality into the endpoints, with entities linking to their canonical URLs. Pagination is also something that will be important as my collection grows, but I think I already know how to handle that.

I hope you enjoyed this quick run-through of my first experience using Beanie. The next time you're building an API on top of MongoDB, I recommend you give it a try!

If this was your first exposure to the Aggregation Framework, I really recommend you read our documentation on this powerful feature of MongoDB. Or if you really want to get your hands dirty, why not check out our free MongoDB University course?

>
>
>If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.
>
>