Build a Cocktail API with Beanie and MongoDB
Mark SmithPublished May 09, 2022 • Updated Sep 23, 2022
Rate this tutorial
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:
The promise of Beanie and FastAPI—to just build a model for this data and have it automatically translate the tricky field types, like
Datebetween 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:
I was pleased to see that I could define a
DocumentMetainner 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
Cocktailto refer to
Ingredient, which hasn't been defined at that point. Fortunately, Pydantic's
update_forward_refsmethod 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__.pyfile, contains mostly boilerplate code for initializing FastAPI, Motor, and Beanie:
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
Cocktailmodel I'll be using to Beanie.
The last line adds the
cocktail_routerto Beanie. It's an
APIRouterthat'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.
cocktail_routeris responsible for routing URL paths to different function handlers which will provide data to be rendered as JSON. The simplest handler is probably:
This handler takes full advantage of these facts: FastAPI will automatically render Pydantic instances as JSON; and Beanie
Documentmodels are defined using Pydantic.
Cocktail.find_all()returns an iterator over all the
Cocktaildocuments in the
recipescollection. FastAPI can't deal with these iterators directly, so the sequence is converted to a list using the
If you have the Just task runner installed, you can run the server with:
If not, you can run it directly by running:
And then you can test the endpoint by pointing your browser at "http://localhost:8000/v1/cocktails/".
A similar endpoint for just a single cocktail is neatly encapsulated by two methods: one to look up a document by
_idand 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
Dependsdeclaration that converts the provided
cocktail_idinto a loaded
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
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:
The results, at "http://localhost:8000/v1/ingredients", look a bit like this:
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
recipescollection, in the MongoDB Atlas web interface:
I had to add the
namefield as an "autocomplete" field type.
![The name field must be of type "autocomplete"](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/old_images/article/beanie-odm-fastapi-cocktails/add_autocomplete_type.png "The name field must be of type "autocomplete"")
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:
$searchaggregation stage specifically uses a search index. In this case, I'm using the
autocompletetype, to match the type of the index I created on the
namefield. 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
Cocktailinstance and just returning a list of strings.
The results are great!
Pointing my browser at "http://localhost:8000/v1/cocktail_autocomplete?fragment=fi" gives me
["Imperial Fizz","Vodka Fizz"], and "http://localhost:8000/v1/cocktail_autocomplete?fragment=ma" gives me
The next step is to build myself a React front end, so that I can truly call this a FARM Stack app.
I was really impressed with how quickly I could get all of this up and running. Handling of
ObjectIdinstances was totally invisible, thanks to Beanie's
PydanticObjectIdtype, and I've seen other sample code that shows how BSON
Datevalues 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.