A mildly interesting software dev. Probably watching anime right now.
It wouldn’t be an overstatement to say that REST APIs power the web. Everything from social networks to the apps that help you order pizza is powered by REST APIs. In fact, mobile apps, enterprise applications, and even games need to talk to servers once in a (very short) while. There’s no point in limiting REST API tutorials to just web developers.
Tornado is a mature, battle-tested web framework written in Python. Motor is an async driver for MongoDB that integrates really well with Tornado. These are going to be the two main tools we will be working as we create our superhero API.
Before we begin, please ensure that you have:
On Ubuntu and similar systems, venv and pip can be easily installed using:
$ sudo apt install python3-pip python3-venv
Create a virtual environment for our new project.
$ mkdir heroes $ cd heros $ python3 -m venv env
Install the project dependencies.
$ source env/bin/activate $ pip install tornado motor
Create a folder named heroes inside the project folder (which is confusingly also named heroes but this is how things are!). This folder will contain our .py files.
Connecting the MongoDB driver to Tornado is simpler than most web frameworks.
Add a /heroes endpoint that allows CRUD operations for the hero resource.
Two routes are added to the app. One for the /heroes endpoint and another for the /heroes/<hero_id> endpoint. While the former is the general endpoint for the resource, the latter is used for operations on a single item.
The changes in handlers.py are too many to show in a diff. Please check the complete source code listing below.
A tree view of the heroes project folder.
heroes ├── heroes │ ├── app.py │ ├── handlers.py │ └── __pycache__ └── env ├── bin ├── include ├── lib ├── lib64 -> lib └── pyvenv.cfg
7 directories, 3 files
$ source env/bin/activate $ export PORT=8080 $ export MONGO_CONNECT_URI=mongodb://localhost:27017 $ python3 -m heroes.app
The API server should now be up and running. Let’s hit the endpoints and check the results.
httpie is a great library for consuming APIs from the command line. You can install it using:
$ pip install httpie
We have built a really cool REST API but it is far from being production-ready. Our API can be a lot more robust and user-friendly. If you want to learn more,
Thanks for reading, drop a few claps if you enjoyed it. Check out some other posts I’ve written, follow and reach out to me on Linkedin.