SlideShare a Scribd company logo
geeksforgeeks.org
FastAPI Rest Architecture
GeeksforGeeks
13–16 minutes
FastAPI is a modern web framework for building APIs with Python.
When developing a RESTful API with FastAPI, you can follow a
REST architectural style, which stands for Representational State
Transfer. In this article, we will learn about the FastAPI-Rest
Architecture. Before going let’s understand the following concepts:
• FastAPI is a modern, fast (high-performance), web framework for
building APIs with Python 3.6+ based on standard Python type
hints. It is designed to be easy to use, efficient, and reliable, making
it a popular choice for developing RESTful APIs and web
applications.
• Representational State Transfer (REST) is an architectural style
that defines a set of constraints to be used for creating web
services. REST API is a way of accessing web services in a simple
and flexible way without having any processing.
Fundamentals of Rest APIs
Resources: RESTful APIs use the concept of resources to
represent data. Resources can be anything, such as users,
products, or orders.
HTTP Methods: RESTful APIs use HTTP methods or verbs to
perform CRUD (create, read, update, and delete) operations on
resources.
There are 39 different methods available. However, here are five
main methods used in REST API:
• GET – Retrieves a specific resource or collection of resources.
• POST – Creates a new resource.
• PUT – Updates an existing resource.
• DELETE – Deletes a specific resource.
• PATCH – Partially updates an existing resource
Representation: RESTful APIs serialize and deserialize data using
different formats. The most common representation is JSON.
FastAPI Architecture Overview
Here is an overview of the key concepts of REST architecture in
FastAPI:
• Asynchronous Support: FastAPI is asynchronous by default,
meaning it can handle multiple concurrent connections efficiently.
This is important for building high-performance APIs.
• RESTful Routing: FastAPI follows RESTful principles, which
define routes (endpoints) for the API, each of which maps to a
specific HTTP method and a resource (e.g., user, product).
• Data Validation: FastAPI uses pydantic models to design request
and response structures for data. Implementation of automatic data
validation and serialization reduces the possibility of error.
• Automatic API Documentation: Dynamic API documentation
(Swagger/OpenAPI) is automatically generated using FastAPI. This
helps developers verify and fully understand the API without the
need for manual documentation.
• Dependency Injection: Dependencies can be used to manage
common logic, such as database connection or authentication. It
supports problem separation and code reuse.
• Request and Response Handling: FastAPI makes it simple to
handle incoming requests and generate responses. It supports
JSON parsing and validation and provides simple ways to retrieve
request data, parameters, and headers.
• Authentication and Authorization: FastAPI can be integrated with
various authentication methods and authorization frameworks,
effectively securing the API.
• CORS Support: It includes built-in cross-origin resource sharing
(CORS) support, making it easy to handle API requests from
different domains.
• Middleware: FastAPI supports custom middleware, which enables
adding pre-processing and post-processing logic to requests and
responses.
• WebSocket Support: FastAPI goes beyond REST and provides
WebSocket features for real-time communication across apps.
• Integration with Other Libraries: FastAPI makes it possible to use
pre-existing technologies by easily integrating with other Python
libraries and frameworks, including SQLAlchemy, databases, and
ORM.
FastAPI to Build REST APIs
Step 1: Installing Necessary Libraries
First, set up a FastAPI project. Create a directory for the project
and install Python and FastAPI:
Install Uvicorn (Asynchronous Gateway Interface to Server)
pip install fastapi
pip install uvicorn
Step 2: Create a Python file, for example, main.py.
Step 3: Defing Models for storing Data.
Define models for users, products, and orders. These models will
be used to validate the request and response data.
The provided code defines three data models (User, Product,
and Order) using Pydantic. These models describe the structure
and types of data for users, products, and orders in a Python
application. Pydantic simplifies data validation and parsing by using
type hints.
• Python3
Python3
from pydantic import BaseModel
class User(BaseModel):
username: str
email: str
class Product(BaseModel):
name: str
price: float
class Order(BaseModel):
user_id: int
product_id: int
Step 4: Initializing the Dictionary.
In main.py, create a FastAPI app and in-memory databases for
users, products, and orders.
This code sets up a FastAPI application and initializes three
dictionaries (users_db, products_db, and orders_db) to store
data. The dictionaries are typed to ensure they hold specific data
structures: users_db stores user data, products_db stores
product data, and orders_db stores order data. These dictionaries
are intended to be used as a basic in-memory database for the
FastAPI application.
• Python3
Python3
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Dict
app = FastAPI()
users_db: Dict[int, User] = {}
products_db: Dict[int, Product] = {}
orders_db: Dict[int, Order] = {}
Step 5: Creating the Endpoints
Create endpoints for all operations performed by the API. Here’s an
example of how to add a new user.
This code defines a FastAPI endpoint at “/users/” that allows users
to create new user records. When a POST request is made with
user data in the request body, a unique user ID is generated, and
the user’s data is stored in the “users_db” dictionary. The
response includes the assigned user ID and the user’s data in the
specified format.
• Python3
Python3
@app.post("/users/", response_model=User)
async def create_user(user: User):
user_id = len(users_db) + 1
users_db[user_id] = user
return {"user_id": user_id, **user.dict()}
Step 6: Creating the FastAPI Application.
Finally, add this code to the end of main.py to run the FastAPI app.
This part of the code runs the FastAPI application using UVicorn, a
lightweight ASGI server. It listens on all available network interfaces
(“0.0.0.0”) and port 8000. When this script is executed, the FastAPI
application becomes accessible on that host and port.
• Python3
Python3
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
STEP 7: Test the API, run the FastAPI app using the following
command:
uvicorn main:app –reload
Sending a POST request
{
“username”: “john_doe”,
“email”: “john@example.com”
}
Retrieving a user by user_id
This code defines an API endpoint to retrieve a user by their ID. If
the user exists in the users_db, it returns their information as a
JSON response. If not, it raises a 404 error with a “User not found”
message.
• Python3
Python3
@app.get("/users/{user_id}", response_model=User)
async def read_user(user_id: int):
if user_id not in users_db:
raise HTTPException(status_code=404,
detail="User not found")
return {"user_id": user_id,
**users_db[user_id].dict()}
Making a GET request
GET http://127.0.0.1:8000/users/{user_id}
GET http://127.0.0.1:8000/users/1
Full code
This code defines several API endpoints for managing users,
products, and orders:
1. Create a New Product: This endpoint allows you to create a new
product and returns the product’s information along with its ID.
2. Retrieve a Product by ID: You can retrieve a product by specifying
its ID. If the product is found in the products_db, its information is
returned as a JSON response.
3. Delete a User by ID: We can delete the user by providing the user
id. If the Product is present then it can be deleted.
4. Create a New Order: This endpoint lets you create a new order. It
checks if the specified user and product exist. If successful, it
returns the order’s information and ID.
5. Retrieve an Order by ID: You can retrieve an order by providing its
ID. If the order exists in the orders_db, its details are returned in a
JSON response.
• Python3
Python3
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Dict
from pydantic import BaseModel
class User(BaseModel):
username: str
email: str
class Product(BaseModel):
name: str
price: float
class Order(BaseModel):
user_id: int
product_id: int
app = FastAPI()
users_db: Dict[int, User] = {}
products_db: Dict[int, Product] = {}
orders_db: Dict[int, Order] = {}
@app.post("/users/", response_model=User)
async def create_user(user: User):
user_id = len(users_db) + 1
users_db[user_id] = user
return {"user_id": user_id, **user.dict()}
@app.get("/users/{user_id}", response_model=User)
async def read_user(user_id: int):
if user_id not in users_db:
raise HTTPException(status_code=404,
detail="User not found")
return {"user_id": user_id,
**users_db[user_id].dict()}
@app.delete("/users/{user_id}",
response_model=User)
async def delete_user(user_id: int):
if user_id not in users_db:
raise HTTPException(status_code=404,
detail="User not found")
deleted_user = users_db.pop(user_id)
return deleted_user
@app.post("/products/", response_model=Product)
async def create_product(product: Product):
product_id = len(products_db) + 1
products_db[product_id] = product
return {"product_id": product_id,
**product.dict()}
@app.get("/products/{product_id}",
response_model=Product)
async def read_product(product_id: int):
if product_id not in products_db:
raise HTTPException(status_code=404,
detail="Product not found")
return {"product_id": product_id,
**products_db[product_id].dict()}
@app.post("/orders/", response_model=Order)
async def create_order(order: Order):
if order.user_id not in users_db or
order.product_id not in products_db:
raise HTTPException(status_code=400,
detail="Invalid User or Product")
order_id = len(orders_db) + 1
orders_db[order_id] = order
return {"order_id": order_id, **order.dict()}
@app.get("/orders/{order_id}",
response_model=Order)
async def read_order(order_id: int):
if order_id not in orders_db:
raise HTTPException(status_code=404,
detail="Order not found")
return {"order_id": order_id,
**orders_db[order_id].dict()}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
To create a product, use this endpoint:
POST http://127.0.0.1:8000/products
To retrieve a product by its product_id, use this endpoint:
POST http://127.0.0.1:8000/products/{product_id}
POST http://127.0.0.1:8000/products/1
Repeat these steps to create and test an endpoint to manage
orders.
Access the API documentation at http://127.0.0.1:8000/docs in a
web browser.
API documentation
Benefits of Using FastAPI for REST APIs
1. Performance: FastAPI is one of the fastest Python web
frameworks. In terms of performance, it is equivalent to NodeJS
and Go.
2. Ease of use: FastAPI is designed to be relatively easy to use and
understand. It has a simple and intuitive API design.
3. Powerful features: FastAPI provides many robust features,
including middleware, dependency injection, validation, and
documentation.
4. Scalability: FastAPI is highly adaptable. It can be used to create
APIs that can handle millions of requests per second.
Best Practices for Using FastAPI to Build REST APIs
Here are some best practices for using FastAPI to create REST
APIs:
• Use HTTP methods correctly: Use the correct HTTP methods for
every operation on a resource.
• Use meaningful resource names: Resource names should be
meaningful and descriptive. This will make it easier for developers
to understand and use the API.
• Use JSON for data representation: JSON is the most popular
data format for RESTful APIs. It is also the format most supported
by FastAPI.
• Use Pydantic for data validation: Pydentic is a powerful data
validation library built into the FastAPI. Use Pydentic to verify data
coming in and out of the API to ensure that APIs are secure and
reliable.
• Document APIs: FastAPI automatically create documentation for
the API but still reviews and adds additional documentation as
needed. Make sure the documentation is clear and concise, and
that it provides all the information developers need to use the API.
REST API development is simplified with FastAPI’s combination of
speed, automated validation, user-friendly model, and integrated
document creation, ensuring accuracy and efficient services. It is an
excellent choice for Python developers who want to develop
RESTful APIs, regardless of expertise level.
Ready to dive into the future? Mastering Generative AI and
ChatGPT is your gateway to the cutting-edge world of AI. Perfect
for tech enthusiasts, this course will teach you how to leverage
Generative AI and ChatGPT with hands-on, practical lessons.
Transform your skills and create innovative AI applications that
stand out. Don't miss out on becoming an AI expert – Enroll now
and start shaping the future!
Please Login to comment...
Ad

More Related Content

Similar to FastAPI - Rest Architecture - in english.pdf (20)

A Beginners Guide to Building MicroServices with FastAPI
A Beginners Guide to Building MicroServices with FastAPIA Beginners Guide to Building MicroServices with FastAPI
A Beginners Guide to Building MicroServices with FastAPI
techprane
 
Web Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptxWeb Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best Practices
Jordan Open Source Association
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
REST based API
REST based APIREST based API
REST based API
ijtsrd
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
NamanVerma88
 
Flutter development Lecture 17 full powerpoint
Flutter development Lecture 17 full powerpointFlutter development Lecture 17 full powerpoint
Flutter development Lecture 17 full powerpoint
TayyabArif8
 
Yii Framework Security
Yii Framework SecurityYii Framework Security
Yii Framework Security
Ilko Kacharov
 
Adding Rules on Existing Hypermedia APIs
Adding Rules on Existing Hypermedia APIsAdding Rules on Existing Hypermedia APIs
Adding Rules on Existing Hypermedia APIs
Michael Petychakis
 
Mariana Alupului Inventions
Mariana Alupului InventionsMariana Alupului Inventions
Mariana Alupului Inventions
malupului
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
IRJET Journal
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
Tharindu Weerasinghe
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
Google Developer Students Club NIT Silchar
 
report_vendor_connect
report_vendor_connectreport_vendor_connect
report_vendor_connect
Yash Mittal
 
M meijer api management - tech-days 2015
M meijer   api management - tech-days 2015M meijer   api management - tech-days 2015
M meijer api management - tech-days 2015
Freelance Consultant / Manager / co-CTO
 
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API frameworkSFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
South Tyrol Free Software Conference
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
Tim Burks
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 
The DNA of a great API
The DNA of a great APIThe DNA of a great API
The DNA of a great API
Ciprian Sorlea CSM-CSPO
 
A Beginners Guide to Building MicroServices with FastAPI
A Beginners Guide to Building MicroServices with FastAPIA Beginners Guide to Building MicroServices with FastAPI
A Beginners Guide to Building MicroServices with FastAPI
techprane
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best Practices
Jordan Open Source Association
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
REST based API
REST based APIREST based API
REST based API
ijtsrd
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Flutter development Lecture 17 full powerpoint
Flutter development Lecture 17 full powerpointFlutter development Lecture 17 full powerpoint
Flutter development Lecture 17 full powerpoint
TayyabArif8
 
Yii Framework Security
Yii Framework SecurityYii Framework Security
Yii Framework Security
Ilko Kacharov
 
Adding Rules on Existing Hypermedia APIs
Adding Rules on Existing Hypermedia APIsAdding Rules on Existing Hypermedia APIs
Adding Rules on Existing Hypermedia APIs
Michael Petychakis
 
Mariana Alupului Inventions
Mariana Alupului InventionsMariana Alupului Inventions
Mariana Alupului Inventions
malupului
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
IRJET Journal
 
report_vendor_connect
report_vendor_connectreport_vendor_connect
report_vendor_connect
Yash Mittal
 
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API frameworkSFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
South Tyrol Free Software Conference
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
Tim Burks
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 

Recently uploaded (20)

AWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptxAWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptx
bharatkumarbhojwani
 
50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd
emir73065
 
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdfTOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
NhiV747372
 
Ann Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdfAnn Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdf
আন্ নাসের নাবিল
 
Process Mining at Deutsche Bank - Journey
Process Mining at Deutsche Bank - JourneyProcess Mining at Deutsche Bank - Journey
Process Mining at Deutsche Bank - Journey
Process mining Evangelist
 
Transforming health care with ai powered
Transforming health care with ai poweredTransforming health care with ai powered
Transforming health care with ai powered
gowthamarvj
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docxAnalysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
hershtara1
 
Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Process Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital TransformationsProcess Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital Transformations
Process mining Evangelist
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
Time series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdfTime series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdf
asmaamahmoudsaeed
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
OlhaTatokhina1
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
AWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptxAWS RDS Presentation to make concepts easy.pptx
AWS RDS Presentation to make concepts easy.pptx
bharatkumarbhojwani
 
50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd50_questions_full.pptxdddddddddddddddddd
50_questions_full.pptxdddddddddddddddddd
emir73065
 
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdfTOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
TOAE201-Slides-Chapter 4. Sample theoretical basis (1).pdf
NhiV747372
 
Transforming health care with ai powered
Transforming health care with ai poweredTransforming health care with ai powered
Transforming health care with ai powered
gowthamarvj
 
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
2-Raction quotient_١٠٠١٤٦.ppt of physical chemisstry
bastakwyry
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
What is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdfWhat is ETL? Difference between ETL and ELT?.pdf
What is ETL? Difference between ETL and ELT?.pdf
SaikatBasu37
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
Automation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success storyAutomation Platforms and Process Mining - success story
Automation Platforms and Process Mining - success story
Process mining Evangelist
 
Fundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithmsFundamentals of Data Analysis, its types, tools, algorithms
Fundamentals of Data Analysis, its types, tools, algorithms
priyaiyerkbcsc
 
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docxAnalysis of Billboards hot 100 toop five hit makers on the chart.docx
Analysis of Billboards hot 100 toop five hit makers on the chart.docx
hershtara1
 
Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Process Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital TransformationsProcess Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital Transformations
Process mining Evangelist
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
Time series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdfTime series for yotube_1_data anlysis.pdf
Time series for yotube_1_data anlysis.pdf
asmaamahmoudsaeed
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
2024-Media-Literacy-Index-Of-Ukrainians-ENG-SHORT.pdf
OlhaTatokhina1
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
Ad

FastAPI - Rest Architecture - in english.pdf

  • 1. geeksforgeeks.org FastAPI Rest Architecture GeeksforGeeks 13–16 minutes FastAPI is a modern web framework for building APIs with Python. When developing a RESTful API with FastAPI, you can follow a REST architectural style, which stands for Representational State Transfer. In this article, we will learn about the FastAPI-Rest Architecture. Before going let’s understand the following concepts: • FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. • Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Fundamentals of Rest APIs Resources: RESTful APIs use the concept of resources to represent data. Resources can be anything, such as users, products, or orders. HTTP Methods: RESTful APIs use HTTP methods or verbs to perform CRUD (create, read, update, and delete) operations on resources. There are 39 different methods available. However, here are five main methods used in REST API: • GET – Retrieves a specific resource or collection of resources. • POST – Creates a new resource. • PUT – Updates an existing resource. • DELETE – Deletes a specific resource. • PATCH – Partially updates an existing resource Representation: RESTful APIs serialize and deserialize data using different formats. The most common representation is JSON. FastAPI Architecture Overview Here is an overview of the key concepts of REST architecture in FastAPI: • Asynchronous Support: FastAPI is asynchronous by default, meaning it can handle multiple concurrent connections efficiently. This is important for building high-performance APIs. • RESTful Routing: FastAPI follows RESTful principles, which define routes (endpoints) for the API, each of which maps to a specific HTTP method and a resource (e.g., user, product). • Data Validation: FastAPI uses pydantic models to design request and response structures for data. Implementation of automatic data validation and serialization reduces the possibility of error. • Automatic API Documentation: Dynamic API documentation (Swagger/OpenAPI) is automatically generated using FastAPI. This helps developers verify and fully understand the API without the need for manual documentation. • Dependency Injection: Dependencies can be used to manage
  • 2. common logic, such as database connection or authentication. It supports problem separation and code reuse. • Request and Response Handling: FastAPI makes it simple to handle incoming requests and generate responses. It supports JSON parsing and validation and provides simple ways to retrieve request data, parameters, and headers. • Authentication and Authorization: FastAPI can be integrated with various authentication methods and authorization frameworks, effectively securing the API. • CORS Support: It includes built-in cross-origin resource sharing (CORS) support, making it easy to handle API requests from different domains. • Middleware: FastAPI supports custom middleware, which enables adding pre-processing and post-processing logic to requests and responses. • WebSocket Support: FastAPI goes beyond REST and provides WebSocket features for real-time communication across apps. • Integration with Other Libraries: FastAPI makes it possible to use pre-existing technologies by easily integrating with other Python libraries and frameworks, including SQLAlchemy, databases, and ORM. FastAPI to Build REST APIs Step 1: Installing Necessary Libraries First, set up a FastAPI project. Create a directory for the project and install Python and FastAPI: Install Uvicorn (Asynchronous Gateway Interface to Server) pip install fastapi pip install uvicorn Step 2: Create a Python file, for example, main.py. Step 3: Defing Models for storing Data. Define models for users, products, and orders. These models will be used to validate the request and response data. The provided code defines three data models (User, Product, and Order) using Pydantic. These models describe the structure and types of data for users, products, and orders in a Python application. Pydantic simplifies data validation and parsing by using type hints. • Python3 Python3 from pydantic import BaseModel class User(BaseModel): username: str email: str class Product(BaseModel): name: str price: float class Order(BaseModel): user_id: int product_id: int Step 4: Initializing the Dictionary. In main.py, create a FastAPI app and in-memory databases for users, products, and orders.
  • 3. This code sets up a FastAPI application and initializes three dictionaries (users_db, products_db, and orders_db) to store data. The dictionaries are typed to ensure they hold specific data structures: users_db stores user data, products_db stores product data, and orders_db stores order data. These dictionaries are intended to be used as a basic in-memory database for the FastAPI application. • Python3 Python3 from fastapi import FastAPI from pydantic import BaseModel from typing import Dict app = FastAPI() users_db: Dict[int, User] = {} products_db: Dict[int, Product] = {} orders_db: Dict[int, Order] = {} Step 5: Creating the Endpoints Create endpoints for all operations performed by the API. Here’s an example of how to add a new user. This code defines a FastAPI endpoint at “/users/” that allows users to create new user records. When a POST request is made with user data in the request body, a unique user ID is generated, and the user’s data is stored in the “users_db” dictionary. The response includes the assigned user ID and the user’s data in the specified format. • Python3 Python3 @app.post("/users/", response_model=User) async def create_user(user: User): user_id = len(users_db) + 1 users_db[user_id] = user return {"user_id": user_id, **user.dict()} Step 6: Creating the FastAPI Application. Finally, add this code to the end of main.py to run the FastAPI app. This part of the code runs the FastAPI application using UVicorn, a lightweight ASGI server. It listens on all available network interfaces (“0.0.0.0”) and port 8000. When this script is executed, the FastAPI application becomes accessible on that host and port. • Python3 Python3 if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) STEP 7: Test the API, run the FastAPI app using the following command: uvicorn main:app –reload Sending a POST request { “username”: “john_doe”, “email”: “john@example.com”
  • 4. } Retrieving a user by user_id This code defines an API endpoint to retrieve a user by their ID. If the user exists in the users_db, it returns their information as a JSON response. If not, it raises a 404 error with a “User not found” message. • Python3 Python3 @app.get("/users/{user_id}", response_model=User) async def read_user(user_id: int): if user_id not in users_db: raise HTTPException(status_code=404, detail="User not found") return {"user_id": user_id, **users_db[user_id].dict()} Making a GET request GET http://127.0.0.1:8000/users/{user_id} GET http://127.0.0.1:8000/users/1 Full code This code defines several API endpoints for managing users, products, and orders: 1. Create a New Product: This endpoint allows you to create a new product and returns the product’s information along with its ID. 2. Retrieve a Product by ID: You can retrieve a product by specifying its ID. If the product is found in the products_db, its information is returned as a JSON response. 3. Delete a User by ID: We can delete the user by providing the user id. If the Product is present then it can be deleted. 4. Create a New Order: This endpoint lets you create a new order. It checks if the specified user and product exist. If successful, it returns the order’s information and ID. 5. Retrieve an Order by ID: You can retrieve an order by providing its ID. If the order exists in the orders_db, its details are returned in a JSON response. • Python3 Python3 from fastapi import FastAPI from pydantic import BaseModel from typing import Dict from pydantic import BaseModel class User(BaseModel): username: str email: str
  • 5. class Product(BaseModel): name: str price: float class Order(BaseModel): user_id: int product_id: int app = FastAPI() users_db: Dict[int, User] = {} products_db: Dict[int, Product] = {} orders_db: Dict[int, Order] = {} @app.post("/users/", response_model=User) async def create_user(user: User): user_id = len(users_db) + 1 users_db[user_id] = user return {"user_id": user_id, **user.dict()} @app.get("/users/{user_id}", response_model=User) async def read_user(user_id: int): if user_id not in users_db: raise HTTPException(status_code=404, detail="User not found") return {"user_id": user_id, **users_db[user_id].dict()} @app.delete("/users/{user_id}", response_model=User) async def delete_user(user_id: int): if user_id not in users_db: raise HTTPException(status_code=404, detail="User not found") deleted_user = users_db.pop(user_id) return deleted_user @app.post("/products/", response_model=Product) async def create_product(product: Product): product_id = len(products_db) + 1 products_db[product_id] = product return {"product_id": product_id, **product.dict()} @app.get("/products/{product_id}", response_model=Product) async def read_product(product_id: int): if product_id not in products_db: raise HTTPException(status_code=404, detail="Product not found") return {"product_id": product_id, **products_db[product_id].dict()} @app.post("/orders/", response_model=Order) async def create_order(order: Order): if order.user_id not in users_db or order.product_id not in products_db: raise HTTPException(status_code=400, detail="Invalid User or Product") order_id = len(orders_db) + 1
  • 6. orders_db[order_id] = order return {"order_id": order_id, **order.dict()} @app.get("/orders/{order_id}", response_model=Order) async def read_order(order_id: int): if order_id not in orders_db: raise HTTPException(status_code=404, detail="Order not found") return {"order_id": order_id, **orders_db[order_id].dict()} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) To create a product, use this endpoint: POST http://127.0.0.1:8000/products To retrieve a product by its product_id, use this endpoint: POST http://127.0.0.1:8000/products/{product_id} POST http://127.0.0.1:8000/products/1 Repeat these steps to create and test an endpoint to manage orders. Access the API documentation at http://127.0.0.1:8000/docs in a web browser. API documentation Benefits of Using FastAPI for REST APIs 1. Performance: FastAPI is one of the fastest Python web frameworks. In terms of performance, it is equivalent to NodeJS and Go. 2. Ease of use: FastAPI is designed to be relatively easy to use and understand. It has a simple and intuitive API design. 3. Powerful features: FastAPI provides many robust features, including middleware, dependency injection, validation, and documentation. 4. Scalability: FastAPI is highly adaptable. It can be used to create APIs that can handle millions of requests per second.
  • 7. Best Practices for Using FastAPI to Build REST APIs Here are some best practices for using FastAPI to create REST APIs: • Use HTTP methods correctly: Use the correct HTTP methods for every operation on a resource. • Use meaningful resource names: Resource names should be meaningful and descriptive. This will make it easier for developers to understand and use the API. • Use JSON for data representation: JSON is the most popular data format for RESTful APIs. It is also the format most supported by FastAPI. • Use Pydantic for data validation: Pydentic is a powerful data validation library built into the FastAPI. Use Pydentic to verify data coming in and out of the API to ensure that APIs are secure and reliable. • Document APIs: FastAPI automatically create documentation for the API but still reviews and adds additional documentation as needed. Make sure the documentation is clear and concise, and that it provides all the information developers need to use the API. REST API development is simplified with FastAPI’s combination of speed, automated validation, user-friendly model, and integrated document creation, ensuring accuracy and efficient services. It is an excellent choice for Python developers who want to develop RESTful APIs, regardless of expertise level. Ready to dive into the future? Mastering Generative AI and ChatGPT is your gateway to the cutting-edge world of AI. Perfect for tech enthusiasts, this course will teach you how to leverage Generative AI and ChatGPT with hands-on, practical lessons. Transform your skills and create innovative AI applications that stand out. Don't miss out on becoming an AI expert – Enroll now and start shaping the future! Please Login to comment...
  翻译: