Open In App

FastAPI – Uvicorn

FastAPI is a modern, high-performance, and robust Python web framework used for building REST APIs. It seamlessly integrates with UVICORN, a lightweight ASGI server, which excels in handling multiple connections and events concurrently. The choice of UVICORN for FastAPI is driven by its exceptional performance, ease of integration with FastAPI, and its ability to serve numerous incoming requests. In this article, we will delve deeper into UVICORN, exploring what it is and how it is employed in conjunction with FASTAPI

What is FastAPI?

FastAPI is a cutting-edge web framework designed for Python 3.8 and higher, utilizing standard Python type hints to create APIs. It is built on the foundations of Starlette and Pydantic, delivering several key advantages:



Some key features of FastAPI are:

What is Uvicorn?

UVICORN is an ASGI (Asynchronous Server Gateway Interface) web server implementation tailored for Python. Before ASGI, Python lacked a minimal low-level server interface for asynchronous frameworks. The ASGI specification acts as a bridge, enabling the creation of a common set of tools usable across all async frameworks. UVICORN currently provides support for HTTP/1.1 and WebSockets.



ASGI vs. WSGI

ASGI represents a significant advancement over WSGI (Web Server Gateway Interface). While WSGI is designed for single, synchronous applications that handle a request and return a response, it does not support long-lived connections like WebSocket connections. In contrast, ASGI is asynchronous and accepts three arguments:

ASGI enables multiple incoming and outgoing events for each application simultaneously, allowing the application to remain responsive to user input while background coroutines run.

Command Line Options :

To access all available command line options for UVICORN, use the following command:

uvicorn --help

This will provide a comprehensive list of commands and options that can be used with UVICORN.

QuickStart with UVICORN and FastAPI :

Now that we understand why UVICORN is the preferred server for FASTAPI, let’s take a quick look at how to start a FASTAPI application using UVICORN.

Step 1:

First, install the FASTAPI library and uvicorn library using following commands.

pip install fastapi
pip install uvicorn

Step 2:

Create a simple FASTAPI template in a file named main.py that returns “Hello world” in JSON format.




from typing import Union
from fastapi import FastAPI
 
app = FastAPI()
 
@app.get("/")
def read_root():
    return {"Hello": "World"}

Start the server using the following command:

uvicorn main:app --reload

Here, uvicorn main:app refers to:

Step 3:

Open your browser and navigate to http://localhost:8000/docs to access the HTML page that showcases the API documentation. This page is automatically generated by FastAPI and makes it easy for developers to understand and interact with the API.

Output

UI


Article Tags :