Getting started with FastAPI
Getting started with FastAPI by implementing simple APIs
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
Good programming language frameworks make it easy to produce quality products faster. Great frameworks even make the whole development experience enjoyable. FastAPI is a new Python web framework that’s powerful and enjoyable to use. The following features make FastAPI worth trying:
- Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
- Fast to code: Increase the speed to develop features by about 200% to 300%.
- Fewer 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.
- Open source project and In Browser API testing.
- Auto generated documentation for APIs
- Uses modern Python features like async/await, type hints etc.
- Built-in data validation for almost all the Python data types using Pydantic.
Requirements :
Installation :
Install all required python packages by running the command given below:
$ pip install fastapi uvicorn[standard] pydantic sqlalchemy
Lets! do it:
Now we are ready to start the implementation of the APIs.
Create a directory for your project and create a file main.py
with
# main.py
# Import FastAPI
from fastapi import FastAPI
# Initialize the app
app = FastAPI()
# GET operation at route '/'
@app.get('/')
def root_api():
return {"message" : "Welcome to Balasundar's Technical Blog"}
Start the server
You can start the server with uvicorn by running the below command.
uvicorn main:app --reload
Note: In the command main
refers to the name of the file and app
is the name of the FastAPI instance we created earlier.
Open your browser and enter http://127.0.0.1:8000/
or you can use any API client to send a request to the API.
You will see the JSON response as
{"message":"Welcome to Balasundar's Technical Blog"}
Now you are ready to implement a POST
method.
Let's implement a API to add basic details of a car.
We need a serialzier to parse and validate the request data. The data going to be parsed and validated using pydantic.
Pydantic is a useful library for data parsing and validation. It coerces input types to the declared type (using type hints), accumulates all the errors using ValidationError & it's also well documented making it easily discoverable.
import BaseModel from pydantic in main.py
.
from pydantic import BaseModel
Create a model for car using pydantic BaseModel.
class CarModel(BaseModel):
manufacturer: str
modelName: str
cc: int
onRoadPrice: int
implement the API
@app.post("/cars")
def add_car(car: CarModel):
# add your code
return car
After adding all the code, the final main.py
file should be like this
# main.py
# Import FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
class CarModel(BaseModel):
manufacturer: str
modelName: str
cc: int
onRoadPrice: int
# Initialize the app
app = FastAPI()
# GET operation at route '/'
@app.get('/')
def root_api():
return {"message": "Welcome to Balasundar's Technical Blog"}
@app.post("/cars")
def add_car(car: CarModel):
# add your code
return car
Like GET method we can't test the POST method on a browser. We have to test it using an API client or through Swagger docs.
API Documentation:
FastAPI generates API documentation automatically for us using Swagger.
You can visit the swagger UI by visiting 127.0.0.1:8000/docs
. Also you can test your API endpoints here.
The ReDoc can be accessed from 127.0.0.1:8000/redoc
.
Great job! You've created simple APIs using FastAPI that accepts GET and POST requests with such little code.
Will meet you soon with some complex APIs with database operations.
Hope this helped. Thank you for reading.
Kindly give your feedback and suggestions.