f1, f2: Input features' values
Why FastAPI is fast to run?
12 May 2025 16:40
Server Gateway Interface
API Code +
Webserver are
sent to AWS.
These 2 things
are imp. for any
API.
Use of SGI: Python can't understand
HTTP req, so we need a translator to
convert into this form.
A web server receives client requests, Listens on ports 80 / 443, handles HTTP/HTTPS concerns, and forwards valid API
requests to the application logic (backend), then sends the response back to the client, Distributes traffic across multiple
API servers
This prediction (o/p) need to be sent
to client:
2 types of SGI: But it is pyhton understable, HTTP
(Used in Flask) can't understand it, SGI again
converts it into HTTPS request.
(Used in FASTAPI)
WSGI API code in
Flask is also
synchronous
in nature.
Web Server Gateway Interface
WSGI: Syn:: At a time, only 1 req. can
be handled. If 5 clients, others must
Web Server in Flask wait. (Blocking Mechanism)
is Gunicorn: A bit of latency Werkzeug Library is used interally to
issues, I/O wait times, use it.
debugging is challenging
FastAPI
Asyn Server Gateway Interface
(Allows Concurrent processing,
Lib interanlly used is : Starlette
Web server: Uvicorn: High Performance, Asyn capabilities.
FastAPI is able to use Async/Await feature of python
In async/await, when the API receives a request from Client 1, it is handled by the ASGI server. Instead of blocking while waiting for
the final output (during I/O), the server pauses that request and starts processing requests from other clients. Once the I/O
completes, the execution resumes
2. FastAPIand the Page
Introduction response
1 is returned.
Why FastAPI is fast to code?
12 May 2025 16:41
1. Automatic Input Validation (Pydantic Support)
2. Auto-Generated Interactive Documentation (Documentation automatically generated, as cod
written, eg: this endpoint is for this work.
Also, it is an interactive one.)
3. Seamless Integration with Modern Ecosystem (ML/DL libraries, OAuth, JWT,
SQL Alchemy, Docker, Kubernetes etc.)
FastAPI is built on 2 libraries: Starlette and Pydantic.
Starlette manages how your API receives requests and sends back response.
Pydantic: Data Validation Library, cuz python doesn't have automatic Data Validation,
Used to check if the data coming into your API is correct and in the right format.
FASTAPI SETUP:
1. New folder -> python -m venv myenv -> myenv\Scripts\activate
2. pip install fastapi uvicorn pydantic OR pip install "fastapi[standard]"
3. CODE:
from fastapi import FastAPI
app = FastAPI() # app object (Name can change: myapp, server, standard is app
@[Link]("/") # Route or Endpoint -> Just / is home endpoint
def hello(): # A function for this endpoint
return {'message' : 'Hello World'} # Returns Dictonary here
@[Link]("/about") # Route or Endpoint
def name(): # A function for this endpoint
return {'message' : 'My name is VASU'} # Returns Dictonary
4. For Running this code:
Not dict always returned:
uvicorn file_name([Link]):app --reload
# Route and Endpoints are same thing: Can be used interchangebly
For auto generated documentation, in the URL generated in terminal, add /docs: eg: [Link]:8000/docs
2. FastAPI Introduction Page 2
CODE: [Link]
Project Overview
14 May 2025 15:06
All options of CRUD available in this app demo.
{ view all patients
3. HTTP Methods (GET) Page 3
HTTP Methods
14 May 2025 15:06
Based on user interaction, s/w can be divided into:
(2 way communication b/w user and s/w
(very less user interaction)
-> Info. receive mostly
HTTP: Protocol handling communication
between client and ser ver.
3. HTTP Methods (GET) Page 4
Path Params
15 May 2025 16:14
Path parameters are dynamic segments of a URL path used to identify a specific
resource.
3/4: Dynamic parts
@[Link]('/name/{id}')
The Path() function in FastAPI is used to provide metadata, validation
rules, and documentation hints for path parameters in your API
endpoints.
Title Enhanced Readability / Documentation
Description
Example
... -> Three dots indicate: required
ge, gt, le, lt
(Although all path params are required,
Min_length
but this is a good way.)
Max_length
regex
4. Path Params and Query Params Page 5
EX. USE CASE:
Instead of returning 200: Patient ID not found
return 404
4. Path Params and Query Params Page 6
Query Parameter
15 May 2025 18:17
sort_by and order both are optional
If not specified: show in default order
4. Path Params and Query Params Page 7
---
OPEN THIS:
## Multiple-value (List) Query Parameters TYPES OF QUERY PARAMETERS:
Same key repeated multiple times.
```
/products?category=books&category=electronics
```
```python
from typing import List
@[Link]("/products")
def products(category: List[str]):
...
```
Used for filters & tags
---
##Boolean Query Parameters
Used for flags.
```
/search?active=true
```
```python
@[Link]("/search")
def search(active: bool):
...
```
FastAPI auto-converts `"true"`, `"false"`
---
## Enum / Restricted-value Query Parameters
Only **allowed values** are accepted.
```python
from enum import Enum
class SortOrder(str, Enum):
asc = "asc"
desc = "desc"
@[Link]("/items")
def items(sort: SortOrder):
...
```
```
/items?sort=asc
```
Prevents invalid input
---
##Query Parameters with Validation
Limits, ranges, length, regex.
```python
from fastapi import Query
@[Link]("/items")
def items(
price: int = Query(gt=0, lt=10000),
): 4. Path Params and Query Params Page 8
...
CODE: [Link]
Pydantic Working of Pydantic: 3 Steps
17 May 2025 18:37
from pydantic import BaseModel is necessary every time.
All further classes will inherit this BaseModel class::
class Patient(BaseModel):
name:str
gender:str
Filed Validator: Used for data/value validation, along with metadata/optional specifications.
Model Validator: Check the dependencies among different fields in a single class/model.
Computed Fields: Fields dynamically created using existing fields
Nested Model: In pydantic, we use one model/class as a field in another model/class.
Pydantic Model Objects can be exported as Python Dictionaries or JSON Objects : Used in building APIs, data export.
([Link])
1. model_dump() -> Convert model objects into Python Dictionary
2. model_dump_json() -> Convert model objects into JSON format. (Python will receive as class 'str' though)
Pydantic Page 9
Recap
21 May 2025 17:16
5. POST Page 10
Plan of action
21 May 2025 17:22
A request body is the portion of an HTTP request that
contains data sent by the client to the server. It is
typically used in HTTP methods such as POST, or PUT to
transmit structured data (e.g., JSON, XML, form-data) for
the purpose of creating or updating resources on the
server. The server parses the request body to extract the
necessary information and perform the intended
operation.
Steps for creating
a new patient Client will send the http request (POST) type.
record. Information (Request body) is sent in JSON format.
(DataBase)
5. POST Page 11
Project Progress
22 May 2025 15:59
6. PUT and DELETE Page 12
STEPS:
Update endpoint
22 May 2025 17:04 Old pydantic model can't be used, since all
fields were compulsory in that, and if used
again, it wil expect all things to get updated.
(what to change
eg: city : new_value)
6. PUT and DELETE Page 13
RECAP
Plan of Attack
27 May 2025 16:30
(Patient Management System)
NOW WHAT TO LEARN:
7. Serving the ML model Page 14
Flow Diagram
27 May 2025 16:52
7. Serving the ML model Page 15
Step 1 - Building & Exporting the Model
28 May 2025 12:50
New features made by Feature Engineering:
-> This data is given to Model
7. Serving the ML model Page 16
Step 2 - Building the API Endpoint
28 May 2025 13:27
POST http request
is used when the client wants to send
some data to server, and wants the server to process it
IN MOSTLY ML/DL MODELS: POST IS USED.
# Here, we ask the user original data only, and in our endpoint, we will create the new data.
7. Serving the ML model Page 17
Recap
02 June 2025 17:24
8. Best Practices for API Page 18
CODE: [Link]
Improvements
02 June 2025 17:26
1. Create a new folder
2. Field validator for city feature
3. Add routes
a. Home
b. Health check
4. Add model version
5. Separation of logic
a. Pydantic model
b. City tier
c. ML logic
6. Try catch
7. Add confidence score
8. Response Model
Response Model:
Validate the output data coming from the API also,
and not only input data.
(Using Pydantic only)
In the code above, it is schema/prediction_response.py
For deployment / industry ready APIs, an API should have a separate folder related to that.
To get the list of all libraries used in the project: pip freeze > [Link]
Health check endpoint is used to verify that the API service is up and running. Returns simple status like 200 OK. Often used by
load balancers, Kubernetes, AWS, Docker, monitoring tools.
@[Link]("/health")
def health():
return {"status": "ok"}
GET /health
OUTPUT: { -> Home endpoint: Human Readable
"status": "ok" ->Health endpoint: Machine Readable.
}
Get the model version using mlflow, and show
it in health check endpoint.
8. Best Practices for API Page 19
Recap
05 June 2025 18:12
9. Dockerization Page 20
DOCKER IMAGE LINK FOR THIS PROJECT: [Link]
premium-api/general
Steps to create a Docker Image
05 June 2025 18:52
Setup
1. Install Docker
2. Create account on Docker Hub
Step 1 - Create a Dockerfile
Step 2 - Build the docker image [docker build -t tweakster24/insurance-
premium-api .]
Step 3 - Login to Docker Hub [docker login]
Step 4 - Push the image to Docker Hub [docker push tweakster24/insurance-
premium-api]
Step 5 - Pull the docker image
Step 6 - Run the docker image locally [docker run -p 8000:8000
tweakster24/insurance-premium-api]
9. Dockerization Page 21
Recap
06 June 2025 16:52
10. Deployment Page 22
Steps for Deployment
06 June 2025 16:52
1. create an EC2 instance
2. Connect to the EC2 instance
3. Run the following commands
a. sudo apt-get update
b. sudo apt-get install -y [Link]
c. sudo systemctl start docker
d. sudo systemctl enable docker Enable cuz: If EC2 server is down, and when it will be up
again, we don't have to manually write start command,
docker's services will automatically run.
e. sudo usermod -aG docker $USER
(Permission granted to EC2 to download an image from an external hub: docker hub. )
f. exit
4. Restart a new connection to EC2 instance
5. Run the following commands
(Image pulled from docker
a. docker pull tweakster24/insurance-premium-api:latest
hub to EC2 ser ver.)
b. docker run -p 8000:8000 tweakster24/insurance-premium-api (Run instance.)
6. change security group settings
7. Check the API
8. Change the frontend code
10. Deployment Page 23