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)

PDF
Serving ML easily with FastAPI
Sebastián Ramírez Montaño
 
PPTX
Springboot Microservices
NexThoughts Technologies
 
PPTX
Web api
Sudhakar Sharma
 
PDF
Autoscaling Kubernetes
craigbox
 
PPTX
Introduction to Scala
Rahul Jain
 
PDF
Spring boot
Bhagwat Kumar
 
PDF
Api Gateway
KhaqanAshraf
 
PDF
REST APIs with Spring
Joshua Long
 
PPT
Asynchronous Programming in C# - Part 1
Mindfire Solutions
 
PDF
Kappa vs Lambda Architectures and Technology Comparison
Kai Wähner
 
PPTX
Microsoft Azure Technical Overview
gjuljo
 
PPTX
Vpc (virtual private cloud)
RashmiDhanve
 
PDF
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
PDF
GraalVM Native and Spring Boot 3.0
MoritzHalbritter
 
PDF
Fastapi
VikasYadav314092
 
PDF
Spring Boot
Pei-Tang Huang
 
PDF
Introduction to Kong API Gateway
Yohann Ciurlik
 
PDF
API Security Best Practices & Guidelines
Prabath Siriwardena
 
PPSX
Rest api standards and best practices
Ankita Mahajan
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
Serving ML easily with FastAPI
Sebastián Ramírez Montaño
 
Springboot Microservices
NexThoughts Technologies
 
Autoscaling Kubernetes
craigbox
 
Introduction to Scala
Rahul Jain
 
Spring boot
Bhagwat Kumar
 
Api Gateway
KhaqanAshraf
 
REST APIs with Spring
Joshua Long
 
Asynchronous Programming in C# - Part 1
Mindfire Solutions
 
Kappa vs Lambda Architectures and Technology Comparison
Kai Wähner
 
Microsoft Azure Technical Overview
gjuljo
 
Vpc (virtual private cloud)
RashmiDhanve
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Edureka!
 
GraalVM Native and Spring Boot 3.0
MoritzHalbritter
 
Spring Boot
Pei-Tang Huang
 
Introduction to Kong API Gateway
Yohann Ciurlik
 
API Security Best Practices & Guidelines
Prabath Siriwardena
 
Rest api standards and best practices
Ankita Mahajan
 
Spring boot Introduction
Jeevesh Pandey
 

Similar to Clean architectures with fast api pycones (20)

PPT
Web Oriented Architecture at Oracle
Emiliano Pecis
 
PDF
GaurabDey_UFL_CV_fulltime (1)
Gaurab Dey
 
PPTX
Webinar september 2013
Marc Gille
 
PDF
Archonnex at ICPSR
Harshakumar Ummerpillai
 
PPTX
Nasdanika Foundation Server
Pavel Vlasov
 
PPTX
Databasecentricapisonthecloudusingplsqlandnodejscon3153oow2016 160922021655
Getting value from IoT, Integration and Data Analytics
 
PPTX
Day 1 - Technical Bootcamp azure synapse analytics
Armand272
 
DOC
Resume_Brad_Johnson
Bradlee Johnson
 
PDF
Using Istio to Secure & Monitor Your Services
Alcide
 
PDF
exploring-spring-boot-clients.pdf Spring Boot
baumi3
 
PPT
Technology Overview
Liran Zelkha
 
PDF
ColbyBackesPortfolio_HighRes
Colby Backes
 
PDF
Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)
Beat Signer
 
PDF
Cloud Readiness : CAST & Microsoft Azure Partnership Overview
CAST
 
PPTX
Apache Airavata SGCI Webinar 8 April 2020
Marlon Pierce
 
PPT
Dojo - from web page to web apps
yoavrubin
 
PDF
Apache Samza 1.0 - What's New, What's Next
Prateek Maheshwari
 
PDF
События, шины и интеграция данных в непростом мире микросервисов / Валентин Г...
Ontico
 
PPTX
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
PDF
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
Lorenzo Carnevale
 
Web Oriented Architecture at Oracle
Emiliano Pecis
 
GaurabDey_UFL_CV_fulltime (1)
Gaurab Dey
 
Webinar september 2013
Marc Gille
 
Archonnex at ICPSR
Harshakumar Ummerpillai
 
Nasdanika Foundation Server
Pavel Vlasov
 
Databasecentricapisonthecloudusingplsqlandnodejscon3153oow2016 160922021655
Getting value from IoT, Integration and Data Analytics
 
Day 1 - Technical Bootcamp azure synapse analytics
Armand272
 
Resume_Brad_Johnson
Bradlee Johnson
 
Using Istio to Secure & Monitor Your Services
Alcide
 
exploring-spring-boot-clients.pdf Spring Boot
baumi3
 
Technology Overview
Liran Zelkha
 
ColbyBackesPortfolio_HighRes
Colby Backes
 
Web Application Frameworks - Lecture 05 - Web Information Systems (4011474FNR)
Beat Signer
 
Cloud Readiness : CAST & Microsoft Azure Partnership Overview
CAST
 
Apache Airavata SGCI Webinar 8 April 2020
Marlon Pierce
 
Dojo - from web page to web apps
yoavrubin
 
Apache Samza 1.0 - What's New, What's Next
Prateek Maheshwari
 
События, шины и интеграция данных в непростом мире микросервисов / Валентин Г...
Ontico
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
tdc-globalcode
 
OpenStack Identity - Keystone (kilo) by Lorenzo Carnevale and Silvio Tavilla
Lorenzo Carnevale
 
Ad

Recently uploaded (20)

PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
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