Creating First REST API with FastAPI
FastAPI :
FastAPI is modern Web Framework . It is used for building API and is very easy to learn .
Features of FastAPI :
- High Performance than many Web Frameworks, faster than Node.js, etc .
- Easy to Develop API’s
- Production Ready
- Well Documentation to learn code fast
- Swagger UI to form API Documentation
- Avoid Redundancy of Code
- Easy Testing
- Support for GraphQL, Background Fetching, Dependency Injection
CREATING REST API USING FastAPI :
- Install Python 3 and pip/pip3 according to your Operating System
- Now, install fastapi using pip or pip3 :
pip install fastapi
- Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :
pip install uvicorn
- Now create a main.py file and import fastapi, also create a server
from fastapi import FastAPI app = FastAPI()
- Now, let’s add the code for sample get request as shown below :
@app.get("/") def read_root(): return {"Hello": "World"}
- Hence, the main.py file will look like :
from
fastapi
import
FastAPI
app
=
FastAPI()
@app
.get(
"/"
)
def
first_example():
"""
GFG Example First Fast API Example
"""
return
{
"GFG Example"
:
"FastAPI"
}
- Now, start the server using
uvicorn main:app --reload
- Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs
You will be able to see the Swagger UI Home page as below : - Expand the “First Example” :
- Now try to Execute the API, you will get the success status with 200 code .
The Response will be {“GFG Example”: “FastAPI”} as shown below :
Please Login to comment...