DEV Community

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

Posted on

Building REST API in Python with Starlette and Docker

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

https://github.com/mdabrowski-eu/starlette-docker-example

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 main.py 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

http://localhost:9999/asdf

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

{"message":"Hello,asdf"}

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

Top comments (0)