Member-only story
Create a fast auto-documented, maintainable and easy-to-use Python API in 5 lines of code with FastAPI (part 1)
Perfect for (unexperienced) developers who just need a complete, working, fast and secure API
You have a great python program that you want to make available to the world. With FastAPI you can speedily create a superfast API that’ll allow you to make your Python code available for other users.
In this article we’re going to create an API in 5 lines of code. What? Five lines?! That’s right; FastAPI isn’t called FastAPI because it is many times faster than frameworks like Django or Flask; it’s also super easy and fast to set up.
After we’ve created our initial API we’ll expand it the next part(s), demonstrating all the necessary bits of knowledge you need to create a fully functional, superfast, production-ready API. Let’s code!
Introduction to FastAPI
Let’s first a really quick look at our framework. FastAPI is a modern, open-source, fast, and highly performant Python web framework used for building Web APIs. Applications running under Uvicorn rank as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (wich are used internally by FastAPI). Sounds good right? Let’s waste no more words and see how to use it.
Installation
Installation is pretty simple. We’ll first install FastAPI with PIP. Then we also need to install Uvicorn. This is the web server on which FastAPI runs.
pip install fastapi uvicorn
It is recommended to install Python dependencies in a virtual environment. This way you keep your projects disentangled. Check out this article for simple instructions on how to use a virtual environment.
Creating our API
All necessary tools are installed, let’s create our API with a single route at the root in five lines. We’ll create a file called main.py
: this file will be the main entrypoint for our app and will define our API. Insert the code below:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def simple_route()…