EventGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50!Learn more >>
MongoDB Developer
Python
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Pythonchevron-right

Build a Cocktail API with Beanie and MongoDB

Mark Smith6 min read • Published May 09, 2022 • Updated Sep 23, 2022
FlaskAtlasPython
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
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 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:
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:
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.
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:
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:
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/".
I drink too many
cocktails
I drink too many cocktails
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.
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:
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 recipes collection, in the MongoDB Atlas web interface:
Create a new search index on the recipes collection
Create a new search index on the `recipes` collection
I had to add the name field 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:
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 "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 ["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.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Quickstart

MongoDB Change Streams with Python


Sep 23, 2022 | 9 min read
Tutorial

Semantic Search Made Easy With LangChain and MongoDB


Dec 11, 2023 | 4 min read
Tutorial

Getting Started with MongoDB and AWS Codewhisperer


Nov 06, 2023 | 3 min read
Tutorial

Boosting AI: Build Your Chatbot Over Your Data With MongoDB Atlas Vector Search and LangChain Templates Using the RAG Pattern


Jan 16, 2024 | 7 min read
Table of Contents
  • Wrap-Up