DEV Community

Cover image for Building REST API in Python with Starlette and Docker

Building REST API in Python with Starlette and Docker

mdabrowskieu profile image mdabrowski-eu ・2 min read

RESTful services are one of the building blocks of modern web. In this article we will build a simple REST app with effective and easy-to-use tools, Starlette and Docker.

Just give me the code

What is Starlette?

Starlette is a relatively new web framework and while it is not as popular as for example Flask, it is still worth attention. It features very competitive performance (check out here benchmark here) and support for ASGI - modern, asynchronous successor of WSGI standard.

What is Docker?

Docker is a light virtualization tool, the most popular of its kind. It enables you to build, distribute and run applications on any system host supporting Docker. While teaching you how to use Docker is not the purpose of this article (assuming that you are not familiar with this tool), I believe it is a good practice to "think in Docker" from the beginning. In my opinion in a lot of cases Docker is (counterintuitively) faster and easier as its existing images take from us some setup and configuration burden.

Let's build some REST service

Firstly, install Starlette.

pip install starlette

Create in app directory in your project and import Starlette there.

At this point we could skip to the "Run it!" step and our app would work, albeit it would be rather dull. To make it more interesting we need to add an endpoint.
We will do that with a simple GET endpoint responding* with RESTful "Hello World" equivalent.
*If you don’t know what this "GET" means, some reading about HTTP methods should clarify things.

Ok, this is not much but it will let us see if our application is indeed working.

Run it!

We will run our app inside a Docker container and for that we need to write a Dockerfile. We are in luck: an image that installs and configures Starlette and uvicorn (ASGI server) is already made. Our job will be limited to copying the correct files.

Let’s build the docker image.

docker build -t starlette-example .

When it is done, execute it:

docker run -d --name starlette -p 9999:80 starlette-example

I mapped 80 port inside container to 9999 to avoid conflicts with httpd service running on my computer but you can choose whichever port you like (unless it is taken or restricted).
Now we can go to browser and type something like


and we should get a nice JSON response as a result:


That’s it! Our simple REST API runs inside a Docker container and properly responds on requests!

Discussion (0)

Editor guide