Open In App

Introduction to FastAPI And Installation

Introduction to FastAPI

FastAPI is a modern, fast (as the name suggests), and highly performant Python web framework used for building APIs. It is built on top of standard Python-type hints and is powered by asynchronous programming using Python’s “asyncio”. FastAPI is known for its speed, simplicity, and ease of use, making it a popular choice for developing APIs.

(Visit the FastAPI website from here.)



Features of FastAPI

Key features are:

Installation for FastAPI

The setup of FastAPI is actually quite simple and straightforward. I have deduced the installation in the following steps: –



Step 1: Set a project directory. Open the terminal and create a virtual environment inside that directory. Creating a virtual environment is necessary, so that we can isolate the FastAPI inside the single folder. (Check out how to set up a python virtual environment here.)

Step 2: Activate your virtual environment.

Step 3: Now, install the FastAPI. Run the command given below!

pip install FastAPI

On pip install fastapi

Step 4: You will also need an ASGI server for the production as well such as uvicorn or hypercorn. We are using uvicorn here. So, go run the following command in terminal.

pip install "uvicorn[standard]" 

On pip install ‘uvicorn [standard]”

Step 5: Now, finally its coding time. Open your editor and navigate to your project directory.

Step 6: Create a file name “main.py”. Give it any name you want.

Step 7: Code it!!

A small FastAPI Application

Let’s see the code:

Line 2: Import FastAPI from the fastapi package.

line 5: Create a variable named “app” to store FastAPI instance. Note that this “app” will be used to start the server.

line 8: This decorator declares the routes for us. Here, it is pointing towards “https://localhost:8000/“. You will use it define endpoints of the app. Since, get method is used, we need to use “@app.get(“/”)”.

line 9: Ok, what will happen on the route is defined by the function. FastAPI provides async to make our code asynchronous.

line 10: Finally, we return a dictionary. FastAPI will serialize the dictionary to JSON like format by itself. And this is how our FastAPI works.

Step 8: Run it using the following command in your terminal. Make sure you are into virtual environment and right directory.

" uvicorn main:app --reload "

Step 9: Head over to the browser and type “localhost:8000”. You will see your fastapi is installed and working fine:

localhost:8000

And that’s it! See how much easy and straightforward it is to make API in FastAPI.

Conclusion

This is the simplest intro to the fastest python web framework. We learned what is FastAPI, it’s features and its installation. Go through the FastAPI docs for more advance use.


Article Tags :