SlideShare a Scribd company logo
9
Most read
13
Most read
21
Most read
Clean Architectures
with
PyConES 2021
October 3rd, 2021
We quickly and effectively detect and eliminate online piracy for digital assets
(movies, series, books) and counterfeited products offered in marketplaces,
search engines, social media platforms and apps
Smart Protection is a technological company
committed to fighting online piracy
User Portal
● A portal to interact with all
the services for a customer
● Need to be able to
communicate with different
data sources
● A scalable team and product
● Be agile, speed and iteration
are must
User Portal
The Product
User Portal
Presented today by
Alvaro del Castillo
alvaro.delcastillo@smartprotection.com
Clean
Architectures
● Main components (software artifacts) of the system (structure)
● The relationships (structural and behaviour) between the components
Similar to traditional architecture for buildings but software ones must be
designed for change
Clean Architectures
Software Architectures
«A client-server software architecture pattern in which the
user interface (presentation), functional process logic
(domain) and data access and storage are developed and
maintained as independent modules (Wikipedia).» The
dependency goes from top to bottom each layer just
depending on its bottom one.
What’s wrong with these layers? The data layer becomes
the core of the architecture (database model, tech …)
Clean Architectures
Classical Approach: Layered Architecture
Clean Architectures
Clean Architecture
The domain (policies) is in the core and
it does not depend on external layers. It
won’t change if something external
changes. Outer layers depend on Inner
layers.
Outer layers (mechanisms)
communicates with the core using
in/out ports (interfaces). FastAPI is
mechanism for us: it can be changed
without affecting the domain.
● The outer layers should point to the inner
layers
● The Business logic should not know about
the technology implementations of the
outer layers
● The ports are interfaces and the adapter
implementations
Clean Architectures
Hexagonal Architecture
Using in the
Infrastructure of an Hexagonal
Architecture
● ASGI (WSGI with async) based on Starlette
● Data validation (path, query params, body) with Pydantic
● Work with any web server with ASGI support like uvicorn
You define the endpoints of your remote APIs and link to the logic that
implements them. These are the routes. In the routes you have data models to
receive and deliver the data.
FastAPI
Web framework for building remote APIs
Based on the Scarlette ASGI framework, its performance is one of the
fastest Python frameworks available, and it is comparable with NodeJS.
From Scarlette it also inherits WebSocket support, GraphQL support,
in-process background tasks, session and cookie support
(middleware in general),
CORS, HTTP2 and others.
FastAPI
Async nature: Performance
Pydantic enforces type hints (Python) at runtime, and provides user friendly
errors when data is invalid. And it is fast compared to other validation libraries.
class User(BaseModel):
id: int
name = "Lisa Perez"
signup_ts: Optional[datetime] = None
friends: List[int] = []
class Config:
extra = 'forbid'
external_data = {
"id1": 1,
"id": 1,
"signup_ts": "2021-01-10 10:00",
"friends": []
}
user = User(**external_data)
The payload, path params and query params are validated and converted to
Python models automatically.
FastAPI
Pydantic Data Validation
Real time documentation in different
formats, like OpenAPI, using type hints
and default values and ranges!
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int = Path(None,
example="item_id_value"),
q: str = Query("query")):
return {"item_id": item_id, "q": q}
if __name__ == '__main__':
uvicorn.run('basic:app', host='0.0.0.0', reload=True)
FastAPI
Automatic documentation
"Dependency Injection" means, in programming, that there is a way for your
code (in this case, your path operation functions) to declare things that it
requires to work and use: "dependencies".
The dependencies, which can be nested, are resolved before calling the path
operation function. For example, for authorization before calling the endpoint:
router.add_api_route(path='/save/',
name='save',
methods=['POST'],
endpoint=certificates_api.save,
dependencies=[Depends(get_certificates_jwt_authorizer)],
status_code=status.HTTP_200_OK)
FastAPI
Dependency Injection
And ASGI introduces new features like Background Tasks!
Methods executed once the request is sent to the client.
async def save(
self,
request: Request,
background_tasks: BackgroundTask) -> None:
...
background_tasks.add_task(send_notification_use_case.execute,
notification_command)
FastAPI
Background Tasks
The routes call the path methods. All this logic is part of the API framework.
But the path methods calls the use cases, with the data from the requests
converted to the domain models. These use cases are in the application layer,
which works directly with the domain layer (all of them business logic).
The use cases returns data with domain models, which is converted with
Pydantic to a JSON payload which is sent to the client.
FastAPI
Inside the Hexagon Architecture
Showcase: User Portal
Reports
Assets
Content
Showcase: User Portal
Domains detection
Reports
Infrastructure
Application
Domain FastAPI
External
API
SQL
DB
User
Service
Repository
API
Showcase: User Portal
Hexagonal Architecture
● Team and product scalability
● Ready for change
● Technology independent
Clean Architectures
Benefits
The hexagonal architecture born as an evolution of layered architectures with the goal
of improving the isolation between policies (domain) and mechanisms (db). The
policies (business logic) became the core of the architecture and it does not depend in
how it is used (thanks to the dependency inversion).
FastAPI is an easy to use web framework for creating remote APIs, based on the
newest standards and reusing actual frameworks like Starlette and Pydantic. With it
you can create APIs pretty fast and ready to be moved to production.
Integrating FastAPI in our Hexagonal Architectures is pretty natural: it is just the
mechanism to offer remote APIs based on the domain business logic.
Using FastAPI in the Infrastructure of Hexagonal Architecture
Takeaways
Questions?
Thanks for attending!

More Related Content

What's hot (20)

PPTX
Spring Framework Petclinic sample application
Antoine Rey
 
PDF
REST APIs with Spring
Joshua Long
 
PPSX
Domain Driven Design
Araf Karsh Hamid
 
PDF
Understanding MicroSERVICE Architecture with Java & Spring Boot
Kashif Ali Siddiqui
 
PDF
Serving ML easily with FastAPI
Sebastián Ramírez Montaño
 
ODP
Introduction to Swagger
Knoldus Inc.
 
PDF
AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...
Edureka!
 
PDF
Swagger With REST APIs.pptx.pdf
Knoldus Inc.
 
PDF
20200722 AWS Black Belt Online Seminar AWSアカウント シングルサインオンの設計と運用
Amazon Web Services Japan
 
PDF
Introduction to Kafka Streams
Guozhang Wang
 
PPT
Graphql presentation
Vibhor Grover
 
PPTX
Azure Synapse Analytics Overview (r1)
James Serra
 
PPTX
Kafka connect 101
Whiteklay
 
PDF
From Zero to Hero with Kafka Connect
confluent
 
PDF
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
Amazon Web Services Korea
 
PDF
20190424 AWS Black Belt Online Seminar Amazon Aurora MySQL
Amazon Web Services Japan
 
PDF
Design patterns for microservice architecture
The Software House
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PPTX
Spring Boot+Kafka: the New Enterprise Platform
VMware Tanzu
 
PDF
AWS Black Belt Online Seminar 2017 AWS体験ハンズオン~Deploy with EB CLI編~
Amazon Web Services Japan
 
Spring Framework Petclinic sample application
Antoine Rey
 
REST APIs with Spring
Joshua Long
 
Domain Driven Design
Araf Karsh Hamid
 
Understanding MicroSERVICE Architecture with Java & Spring Boot
Kashif Ali Siddiqui
 
Serving ML easily with FastAPI
Sebastián Ramírez Montaño
 
Introduction to Swagger
Knoldus Inc.
 
AWS Tutorial | AWS Certified Solutions Architect | Amazon AWS | AWS Training ...
Edureka!
 
Swagger With REST APIs.pptx.pdf
Knoldus Inc.
 
20200722 AWS Black Belt Online Seminar AWSアカウント シングルサインオンの設計と運用
Amazon Web Services Japan
 
Introduction to Kafka Streams
Guozhang Wang
 
Graphql presentation
Vibhor Grover
 
Azure Synapse Analytics Overview (r1)
James Serra
 
Kafka connect 101
Whiteklay
 
From Zero to Hero with Kafka Connect
confluent
 
[AWS Dev Day] 실습워크샵 | Amazon EKS 핸즈온 워크샵
Amazon Web Services Korea
 
20190424 AWS Black Belt Online Seminar Amazon Aurora MySQL
Amazon Web Services Japan
 
Design patterns for microservice architecture
The Software House
 
Spring Framework - Core
Dzmitry Naskou
 
Spring Boot+Kafka: the New Enterprise Platform
VMware Tanzu
 
AWS Black Belt Online Seminar 2017 AWS体験ハンズオン~Deploy with EB CLI編~
Amazon Web Services Japan
 

Similar to Clean architectures with fast api pycones (20)

PDF
FastAPI - Rest Architecture - in english.pdf
inigraha
 
PPTX
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
PPTX
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
PDF
A Beginners Guide to Building MicroServices with FastAPI
techprane
 
PDF
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
PDF
5 Things about fastAPI I wish we had known beforehand
Alexander Hendorf
 
PDF
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
PDF
Selecting the Right Python Library for Fast API Solutions
Shiv Technolabs Pvt. Ltd.
 
PDF
Design and Monitoring Performance of Digital Properties
IRJET Journal
 
PDF
I Love APIs Europe 2015: Developer Sessions
Apigee | Google Cloud
 
PDF
Scalable web application architecture
postrational
 
PDF
Building an API with Django and Django REST Framework
Christopher Foresman
 
PDF
IoT Toolkit and the Smart Object API Tutorial Introduction
Michael Koster
 
PDF
IoT Toolkit and Smart Object API Tutorial Introduction
Michael Koster
 
PDF
Smart objectapi tutorial 092013
Michael Koster
 
PDF
Business-friendly library for inter-service communication
Pivorak MeetUp
 
PDF
Chris Mathias Presents Advanced API Design Considerations at LA CTO Forum
Chris Mathias
 
PPTX
The Right Kind of API – How To Choose Appropriate API Protocols and Data Form...
Nordic APIs
 
PDF
A Brief Introduction to Python Developer Frameworks.pdf
paulsapna153
 
PPTX
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
FastAPI - Rest Architecture - in english.pdf
inigraha
 
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
A Beginners Guide to Building MicroServices with FastAPI
techprane
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
5 Things about fastAPI I wish we had known beforehand
Alexander Hendorf
 
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Selecting the Right Python Library for Fast API Solutions
Shiv Technolabs Pvt. Ltd.
 
Design and Monitoring Performance of Digital Properties
IRJET Journal
 
I Love APIs Europe 2015: Developer Sessions
Apigee | Google Cloud
 
Scalable web application architecture
postrational
 
Building an API with Django and Django REST Framework
Christopher Foresman
 
IoT Toolkit and the Smart Object API Tutorial Introduction
Michael Koster
 
IoT Toolkit and Smart Object API Tutorial Introduction
Michael Koster
 
Smart objectapi tutorial 092013
Michael Koster
 
Business-friendly library for inter-service communication
Pivorak MeetUp
 
Chris Mathias Presents Advanced API Design Considerations at LA CTO Forum
Chris Mathias
 
The Right Kind of API – How To Choose Appropriate API Protocols and Data Form...
Nordic APIs
 
A Brief Introduction to Python Developer Frameworks.pdf
paulsapna153
 
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
Ad

Recently uploaded (20)

PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
 
Practical Applications of AI in Local Government
OnBoard
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Ad

Clean architectures with fast api pycones

  • 2. We quickly and effectively detect and eliminate online piracy for digital assets (movies, series, books) and counterfeited products offered in marketplaces, search engines, social media platforms and apps Smart Protection is a technological company committed to fighting online piracy
  • 4. ● A portal to interact with all the services for a customer ● Need to be able to communicate with different data sources ● A scalable team and product ● Be agile, speed and iteration are must User Portal The Product
  • 7. ● Main components (software artifacts) of the system (structure) ● The relationships (structural and behaviour) between the components Similar to traditional architecture for buildings but software ones must be designed for change Clean Architectures Software Architectures
  • 8. «A client-server software architecture pattern in which the user interface (presentation), functional process logic (domain) and data access and storage are developed and maintained as independent modules (Wikipedia).» The dependency goes from top to bottom each layer just depending on its bottom one. What’s wrong with these layers? The data layer becomes the core of the architecture (database model, tech …) Clean Architectures Classical Approach: Layered Architecture
  • 9. Clean Architectures Clean Architecture The domain (policies) is in the core and it does not depend on external layers. It won’t change if something external changes. Outer layers depend on Inner layers. Outer layers (mechanisms) communicates with the core using in/out ports (interfaces). FastAPI is mechanism for us: it can be changed without affecting the domain.
  • 10. ● The outer layers should point to the inner layers ● The Business logic should not know about the technology implementations of the outer layers ● The ports are interfaces and the adapter implementations Clean Architectures Hexagonal Architecture
  • 11. Using in the Infrastructure of an Hexagonal Architecture
  • 12. ● ASGI (WSGI with async) based on Starlette ● Data validation (path, query params, body) with Pydantic ● Work with any web server with ASGI support like uvicorn You define the endpoints of your remote APIs and link to the logic that implements them. These are the routes. In the routes you have data models to receive and deliver the data. FastAPI Web framework for building remote APIs
  • 13. Based on the Scarlette ASGI framework, its performance is one of the fastest Python frameworks available, and it is comparable with NodeJS. From Scarlette it also inherits WebSocket support, GraphQL support, in-process background tasks, session and cookie support (middleware in general), CORS, HTTP2 and others. FastAPI Async nature: Performance
  • 14. Pydantic enforces type hints (Python) at runtime, and provides user friendly errors when data is invalid. And it is fast compared to other validation libraries. class User(BaseModel): id: int name = "Lisa Perez" signup_ts: Optional[datetime] = None friends: List[int] = [] class Config: extra = 'forbid' external_data = { "id1": 1, "id": 1, "signup_ts": "2021-01-10 10:00", "friends": [] } user = User(**external_data) The payload, path params and query params are validated and converted to Python models automatically. FastAPI Pydantic Data Validation
  • 15. Real time documentation in different formats, like OpenAPI, using type hints and default values and ranges! app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int = Path(None, example="item_id_value"), q: str = Query("query")): return {"item_id": item_id, "q": q} if __name__ == '__main__': uvicorn.run('basic:app', host='0.0.0.0', reload=True) FastAPI Automatic documentation
  • 16. "Dependency Injection" means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: "dependencies". The dependencies, which can be nested, are resolved before calling the path operation function. For example, for authorization before calling the endpoint: router.add_api_route(path='/save/', name='save', methods=['POST'], endpoint=certificates_api.save, dependencies=[Depends(get_certificates_jwt_authorizer)], status_code=status.HTTP_200_OK) FastAPI Dependency Injection
  • 17. And ASGI introduces new features like Background Tasks! Methods executed once the request is sent to the client. async def save( self, request: Request, background_tasks: BackgroundTask) -> None: ... background_tasks.add_task(send_notification_use_case.execute, notification_command) FastAPI Background Tasks
  • 18. The routes call the path methods. All this logic is part of the API framework. But the path methods calls the use cases, with the data from the requests converted to the domain models. These use cases are in the application layer, which works directly with the domain layer (all of them business logic). The use cases returns data with domain models, which is converted with Pydantic to a JSON payload which is sent to the client. FastAPI Inside the Hexagon Architecture
  • 22. ● Team and product scalability ● Ready for change ● Technology independent Clean Architectures Benefits
  • 23. The hexagonal architecture born as an evolution of layered architectures with the goal of improving the isolation between policies (domain) and mechanisms (db). The policies (business logic) became the core of the architecture and it does not depend in how it is used (thanks to the dependency inversion). FastAPI is an easy to use web framework for creating remote APIs, based on the newest standards and reusing actual frameworks like Starlette and Pydantic. With it you can create APIs pretty fast and ready to be moved to production. Integrating FastAPI in our Hexagonal Architectures is pretty natural: it is just the mechanism to offer remote APIs based on the domain business logic. Using FastAPI in the Infrastructure of Hexagonal Architecture Takeaways