Start Here: Up and Running with FastAPI

Ethan Cerami
FastAPI Tutorials
Published in
2 min readFeb 26, 2021
Photo by Jenny Hill on Unsplash

FastAPI is a flexible, fast, and easy to learn Python library for creating API endpoints.

Here, I show you how to get up and running with FastAPI in under 5 minutes.

First, make sure you are using Python 3.6+ and install FastAPI via pip:

pip3 install fastapi[all]

You are now ready to create your first endpoint.

As a concrete, but simple example, let’s build an API for a bare-bones Slack clone. It will have four API endpoints:

  • get_status: returns the system status;
  • get_channels: returns a list of channels;
  • post_message: stores a new message; and
  • get_messages: returns a list of messages for a specified channel

First up, let’s create an endpoint for get_status. Here is the complete code:

The “Hello, World!” of FastAPI!

Eight lines of code and you are up and running. Note how FastAPI uses Python decorators to annotate API endpoints. For example, we annotate the get_status method as an HTTP GET endpoint and link it to the URL /status.

To run the example, type

uvicorn slack1:app --reload

Uvicorn is a standalone server application that can run FastAPI applications. The reload option tells Uvicorn to automatically detect and reload any code changes you make. This is not recommended for production environments but can be very useful for local development. To change the default port number or set additional options, refer to the Uvicorn command line options.

Once running, you can go to http://localhost:8000/status, and see your endpoint in action.

Our first FastAPI Up and Running.

As a bonus feature, FastAPI will also create a fully interactive doc site for your API. To access it, go to http://localhost:8000/docs.

API Documentation auto-generated by FastAPI.

If you click the “Try it out” button, you can execute the endpoint and see it in action.

The documentation page also includes a link to an openapi.json file, which defines your API in the Open API Specification. Users can then more easily build client libraries via code generators, such as Swagger CodeGen.

That’s it. Five minutes and you are now up and running with FastAPI.

If you want to dig a little deeper and continue on with the slack clone, check out Fast API: Data Models next.

--

--

Ethan Cerami
FastAPI Tutorials

Director, Knowledge Systems Group @ Dana-Farber Cancer Institute, Boston MA.