FastAPI Introduction

 

FastAPI


Introduction:

FastAPI is a new, high-performance, web framework for building APIs with Python. If we compare FastAPI with other web framework like Flask or Django, FastAPI is very fast and ready to deployment.

Key Features:

  • Fast:- Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). which is one of the fastest python frameworks available.
  • Fast to code:- Increase the speed to develop features by about 200% to 300% in comparison with other web framework.
  • Less Bugs:- Reduce about 40% of human (developer) induced errors.
  • Intuitive:- Great editor support. Completion everywhere. Less time debugging.
  • Easy:- Designed to be easy to use and learn. Less time reading docs.
  • Short:- Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
  • Robust:- Get production-ready code. With automatic interactive documentation.
  • Standards-based:- Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.  


Installation:

To install FastAPI, follow below steps:-
            
    Open terminal and fire below command:
    
            $ pip install fastapi

            we need an ASGI server for production such as uvicorn .

            $ pip install uvicorn

Example:

Create a file  namely, main.py and add below codes:

    from fastapi import FastAPI
from fastapi import FastAPIapp = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

or we add async def also..

Run your code:

To run the server with below command:

    uvicorn main:app --reload

Its will start like this;

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.


We will get the JSON response as:

            {"item_id": 5, "q": "anyquery"}

You already created an API that:

  • Receives HTTP requests in the paths / and /items/{item_id}
  • Both paths take GET operations (also known as HTTP methods).
  • The path /items/{item_id} has a path parameter item_id that should be an int
  • The path /items/{item_id} has an optional str query parameter q


Interactive API docs:

Now go to http://127.0.0.1:8000/docs.
You will see the automatic interactive API documentation (provided by Swagger UI):


Alternative API docs:

And now, go to http://127.0.0.1:8000/redoc.






Learn More:


Documentation:- https://fastapi.tiangolo.com/

Source Code:- https://github.com/tiangolo/fastapi








            





Visitor