SlideShare a Scribd company logo
Parallelisation, aggregation and
validation API with Python
Max Klymyshyn
CTO at CartFresh
@maxmaxmaxmax
‣ 12+ years of experience, 7 years with Python, 6 with JS

‣ Was part of oDesk, Helios, 42cc.

‣ Co-organizer of PyCon Ukraine, KyivJS, Papers We Love

‣ CTO at CartFresh

‣ Challenging myself with english talk. It’s not my first language, bear
with me
About
‣ Grocery Delivery startup

‣ Operating as CartFresh (Boston, US) and ZAKAZ.UA
(Kiev, Dnepropetrovsk, Kharkiv, Ukraine)

‣ Apache CouchDB, Apache Solr, Redis

‣ Heavy python on back-end
CartFresh
‣ Quick overview

‣ Some abstract info about context

‣ Tools for Python
Table of contents
Why API again?
World is changing very quickly:

‣ Mobile apps

‣ Internet of Things

‣ Microservices

‣ Isomorphic apps
Why API again?
Good API is hard
when all your stuff should work together well
‣ Validation

‣ Reusability

‣ Consistency

‣ Maintainability

‣ Scalability
It’s challenging
Good API makes it easier to develop a service
Divide and conquer (D&C)
‣ API expresses a software component in terms of its
operations, inputs, outputs, and underlying types

‣ API helps create reusable building blocks and
communicate between system components

‣ It opens new opportunities to develop new systems
based on your product
Overview
Moving parts
VALIDATION
OUTPUT
BL
INPUT
‣ input – need to be validated for type correctness 

‣ validation – input should be constrained by domain-
specific business rules

‣ business logic – obviously most useful part of the system 

‣ output – data model, serialised into specific format
Moving parts
API creation becomes trivial with good
understanding and right tools
All challenges are behind: how to make it
simple, how to make it maintainable, how
to keep API users updated
Trends during the past few years
‣ RESTification

‣ Data Query Languages

‣ Microservices architecture
Trends
REST
‣ Unified interface to communication protocol between
client and API

‣ Built on top of HTTP

‣ Simple
Data Query Languages
‣ GraphQL

‣ Falcor

‣ Datalog

‣ Datomic
etc.
Data Query Languages
Main point of DQL is to make declarative composition of
queries to simple data structures and

represent it as single data structure
Common case
Monolithic service
Monolite
More realistic case
Microservices
Monolit Microservices
Microservices
Monolit Microservices
Difference
‣ New layer of complexity in terms of input validation

‣ New unreliable layer (network)

‣ Additional protocol overhead

‣ Communication latency
Seriously
‣ You’ll get a chance to improve each piece of code
separately without breaking other part of the system (D&C!)

‣ You can split development of microservices between
different dev teams

‣ You’ll get a lot of fun!
But let’s be optimistic
Tools
‣ SWAGGER – a simple representation of your RESTful API
(OpenAPI initiative), FLEX for Python

‣ RESTful API Modelling Language – RAML

‣ APIDOC – a documentation from API annotations in your
source code

‣ api-blueprint, RESTUnite, apiary etc.
API Frameworks
paths:
/products:
get:
summary: Product Types
description: |
The Products endpoint returns information about the *Uber* products
offered at a given location. The response includes the display name
and other details about each product, and lists the products in the
proper display order.
parameters:
- name: latitude
in: query
description: Latitude component of location.
required: true
type: number
format: double
- name: longitude
in: query
description: Longitude component of location.
required: true
type: number
format: double
tags:
- Products
responses:
200:
description: An array of products
schema:
type: array
items:
$ref: '#/definitions/Product'
Swagger spec example
/products:
uriParameters:
displayName: Products
description: A collection of products
post:
description: Create a product
#Post body media type support
#text/xml: !!null # media type text, xml support
#application/json: !!null #media type json support
body:
application/json:
schema: |
{
"$schema": "http://json-schema.org/draft-03/schema",
"product": {
"name": {
"required": true,
"type": "string"
},
"description": {
"required": true,
"type": "string"
}
RAML spec example
example: |
{
"product": {
"id": "1",
"name": "Product One",
...
}
}
get:
description: Get a list of products
queryParameters:
q:
description: Search phrase to look for products
type: string
required: false
responses:
200:
body:
application/json:
#example: !include schema/product-list.json
RAML spec example
To prevent situation when documentation, client
libraries, and source code get out of sync
CLIENT #1 SERVER CLIENT #2
‣ Predefined input parameters + validation

‣ Predefined response schema (model)

‣ Query Language
Aggregation
GraphQL/Graphene
import graphene
import pprint
data = [1, 2, 3, 4]
class Query(graphene.ObjectType):
hello = graphene.String()
data = graphene.String()
def resolve_data(self, args, info):
return ",".join(map(str, data))
def resolve_hello(self, args, info):
return 'World'
schema = graphene.Schema(query=Query)
result = schema.execute('{ hello, data }')
pprint.pprint(result.data)
# OrderedDict([('hello', u'World'), ('data', u'1,2,3,4')])
GraphQL’s power comes from a simple idea — 
instead of defining the structure of responses
on the server, the flexibility is given to the client.
GraphQL vs REST
GraphQL/graphene allow us

to use our beloved language

for declaration of Model/API Schema: python
GraphQL vs Swagger
Batching
Tools: django-batch-requests
[
{
"method": "get",
"url": "/sleep/?seconds=3"
},
{
"method": "get",
"url": "/sleep/?seconds=3"
}
]
[
{
"headers": {
"Content-Type": "text/html; charset=utf-8",
"batch_requests.duration": 3
},
"status_code": 200,
"body": "Success!",
"reason_phrase": "OK"
},
{
"headers": {
"Content-Type": "text/html; charset=utf-8",
"batch_requests.duration": 3
},
"status_code": 200,
"body": "Success!",
"reason_phrase": "OK"
}
]
Our experience
‣ End up with batched API interface

‣ Declarative input validation with trafaret
‣ Free schema (disadvantage)

‣ Very simple SQL-JOIN-like aggregation
Params, validation, transformation
@validate_args(
_('Invalid request'),
store_id=tr.String() >> pipe(unicode, unicode.strip),
slugs=tr.List(tr.String() >> pipe(unicode, unicode.strip)),
ean=tr.String | tr.Null,
extended=tr.Bool | tr.Null,
query=tr.String | tr.Null,
facets=tr.List(
tr.List(tr.String, min_length=2, max_length=2)) | tr.Null,
sort=tr.String(allow_blank=True) | tr.Null,
_optional=('extended', 'query', 'facets', 'sort', 'ean'))
def resource_products(store, user, session, limit=None, offset=1, lang='en',
args=None, **kwargs):
pass
[
"store.products", {
store_id: Storage.first(“store").id, slugs: [options.slug],
facets: options.facets || [], sort: options.sort || “"
}, {
offset: options.offset || 1, id: "catalog",
join: [{
apply_as: "facets_base",
on: ["slug", "slug"],
request: {
type: "store.facets",
args: {
store_id: "$request.[-2].args.store_id",
slug: "$request.[-2].args.slugs|first"
}
}
}, {
apply_as: "category_tree",
on: ["slug", "requested_slug"],
request: {
type: "store.department_tree",
args: {
store_id: "$request.[-2].args.store_id",
slug: "$request.[-2].args.slugs|first"
}
}
}]
}
]
Thanks.
@maxmaxmaxmax
Ad

Recommended

“Fighting with giants - GraphQL soft adoption at Revolut” by Andrii Los
“Fighting with giants - GraphQL soft adoption at Revolut” by Andrii Los
IlyaDmitriev11
 
Introduction to GraphQL
Introduction to GraphQL
Brainhub
 
GraphQL in an Age of REST
GraphQL in an Age of REST
Yos Riady
 
Better APIs with GraphQL
Better APIs with GraphQL
Josh Price
 
Let's Graph
Let's Graph
Fabien de Maestri
 
Intro to GraphQL
Intro to GraphQL
Rakuten Group, Inc.
 
Taking Control of your Data with GraphQL
Taking Control of your Data with GraphQL
Vinci Rufus
 
GraphQL: Enabling a new generation of API developer tools
GraphQL: Enabling a new generation of API developer tools
Sashko Stubailo
 
VTi Knowledge Database: a LinkedData project
VTi Knowledge Database: a LinkedData project
Tom Klaasen
 
Graphql
Graphql
Niv Ben David
 
GraphQL Introduction
GraphQL Introduction
Serge Huber
 
Polyglot
Polyglot
Rory Preddy
 
Code Generation with giant CRUD
Code Generation with giant CRUD
Tom Klaasen
 
Introduction to GraphQL
Introduction to GraphQL
Rodrigo Prates
 
GraphQL
GraphQL
Cédric GILLET
 
End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013
Alexandre Morgaut
 
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Jon Wong
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays
 
GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)
Chris Grice
 
GraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend Devs
Sashko Stubailo
 
Boost your APIs with GraphQL 1.0
Boost your APIs with GraphQL 1.0
Otávio Santana
 
Neo4J and Grails
Neo4J and Grails
Dmitry Buzdin
 
Overview of modern software ecosystem for big data analysis
Overview of modern software ecosystem for big data analysis
Michael Bryzek
 
Graphql presentation
Graphql presentation
Vibhor Grover
 
The Apollo and GraphQL Stack
The Apollo and GraphQL Stack
Sashko Stubailo
 
GraphQL & Relay
GraphQL & Relay
Viacheslav Slinko
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
Sashko Stubailo
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
Sashko Stubailo
 
Communicating Sequential Processes (CSP) in JavaScript
Communicating Sequential Processes (CSP) in JavaScript
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 

More Related Content

What's hot (20)

VTi Knowledge Database: a LinkedData project
VTi Knowledge Database: a LinkedData project
Tom Klaasen
 
Graphql
Graphql
Niv Ben David
 
GraphQL Introduction
GraphQL Introduction
Serge Huber
 
Polyglot
Polyglot
Rory Preddy
 
Code Generation with giant CRUD
Code Generation with giant CRUD
Tom Klaasen
 
Introduction to GraphQL
Introduction to GraphQL
Rodrigo Prates
 
GraphQL
GraphQL
Cédric GILLET
 
End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013
Alexandre Morgaut
 
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Jon Wong
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays
 
GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)
Chris Grice
 
GraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend Devs
Sashko Stubailo
 
Boost your APIs with GraphQL 1.0
Boost your APIs with GraphQL 1.0
Otávio Santana
 
Neo4J and Grails
Neo4J and Grails
Dmitry Buzdin
 
Overview of modern software ecosystem for big data analysis
Overview of modern software ecosystem for big data analysis
Michael Bryzek
 
Graphql presentation
Graphql presentation
Vibhor Grover
 
The Apollo and GraphQL Stack
The Apollo and GraphQL Stack
Sashko Stubailo
 
GraphQL & Relay
GraphQL & Relay
Viacheslav Slinko
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
Sashko Stubailo
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
Sashko Stubailo
 
VTi Knowledge Database: a LinkedData project
VTi Knowledge Database: a LinkedData project
Tom Klaasen
 
GraphQL Introduction
GraphQL Introduction
Serge Huber
 
Code Generation with giant CRUD
Code Generation with giant CRUD
Tom Klaasen
 
Introduction to GraphQL
Introduction to GraphQL
Rodrigo Prates
 
End-to-end HTML5 APIs - The Geek Gathering 2013
End-to-end HTML5 APIs - The Geek Gathering 2013
Alexandre Morgaut
 
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Why UI Developers Love GraphQL - Sashko Stubailo, Apollo/Meteor
Jon Wong
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays
 
GraphQL @ Manc.JS (March 2018)
GraphQL @ Manc.JS (March 2018)
Chris Grice
 
GraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend Devs
Sashko Stubailo
 
Boost your APIs with GraphQL 1.0
Boost your APIs with GraphQL 1.0
Otávio Santana
 
Overview of modern software ecosystem for big data analysis
Overview of modern software ecosystem for big data analysis
Michael Bryzek
 
Graphql presentation
Graphql presentation
Vibhor Grover
 
The Apollo and GraphQL Stack
The Apollo and GraphQL Stack
Sashko Stubailo
 
GraphQL across the stack: How everything fits together
GraphQL across the stack: How everything fits together
Sashko Stubailo
 
Adding GraphQL to your existing architecture
Adding GraphQL to your existing architecture
Sashko Stubailo
 

Viewers also liked (20)

Communicating Sequential Processes (CSP) in JavaScript
Communicating Sequential Processes (CSP) in JavaScript
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
DotNetCampus
 
API Governance
API Governance
Sunil Kuchipudi
 
Genesi di una tecnologia, dalla ricerca all'industria...
Genesi di una tecnologia, dalla ricerca all'industria...
italianaSoftware
 
Microservizi, scenari del prossimo e del lontano futuro
Microservizi, scenari del prossimo e del lontano futuro
italianaSoftware
 
Performance optimisation with GraphQL
Performance optimisation with GraphQL
yann_s
 
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
italianaSoftware
 
Another API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger Comparison
SmartBear
 
A Framework for Rule-Based Dynamic Adaptation
A Framework for Rule-Based Dynamic Adaptation
IMDS2014
 
La rivoluzione dei Microservizi
La rivoluzione dei Microservizi
italianaSoftware
 
API Management and Integrated SOA Governance
API Management and Integrated SOA Governance
Sumanth Chinthagunta
 
Introduzione ai Microservices
Introduzione ai Microservices
Daniele Mondello
 
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
italianaSoftware
 
IoT and Microservice
IoT and Microservice
kgshukla
 
API Description Languages
API Description Languages
Akana
 
Devops, Cloud e Container
Devops, Cloud e Container
italianaSoftware
 
API Governance in the Enterprise
API Governance in the Enterprise
Apigee | Google Cloud
 
Microservice Architecture JavaCro 2015
Microservice Architecture JavaCro 2015
Nenad Pecanac
 
Architecture for the API-enterprise
Architecture for the API-enterprise
Apigee | Google Cloud
 
Communicating Sequential Processes (CSP) in JavaScript
Communicating Sequential Processes (CSP) in JavaScript
Max Klymyshyn
 
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
Max Klymyshyn
 
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
SVILUPPARE E GESTIRE ARCHITETTURE A MICROSERVIZI SU AZURE
DotNetCampus
 
Genesi di una tecnologia, dalla ricerca all'industria...
Genesi di una tecnologia, dalla ricerca all'industria...
italianaSoftware
 
Microservizi, scenari del prossimo e del lontano futuro
Microservizi, scenari del prossimo e del lontano futuro
italianaSoftware
 
Performance optimisation with GraphQL
Performance optimisation with GraphQL
yann_s
 
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
Industria 4.0 - Come verrà rivoluzionata l'industria italiana
italianaSoftware
 
Another API-Blueprint, RAML and Swagger Comparison
Another API-Blueprint, RAML and Swagger Comparison
SmartBear
 
A Framework for Rule-Based Dynamic Adaptation
A Framework for Rule-Based Dynamic Adaptation
IMDS2014
 
La rivoluzione dei Microservizi
La rivoluzione dei Microservizi
italianaSoftware
 
API Management and Integrated SOA Governance
API Management and Integrated SOA Governance
Sumanth Chinthagunta
 
Introduzione ai Microservices
Introduzione ai Microservices
Daniele Mondello
 
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
Implementazione di una soluzione a microservizi: benifici organizzativi ed ec...
italianaSoftware
 
IoT and Microservice
IoT and Microservice
kgshukla
 
API Description Languages
API Description Languages
Akana
 
Microservice Architecture JavaCro 2015
Microservice Architecture JavaCro 2015
Nenad Pecanac
 
Ad

Similar to PiterPy 2016: Parallelization, Aggregation and Validation of API in Python (20)

Intro to GraphQL
Intro to GraphQL
Charles Burgess
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
FastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdf
inigraha
 
REST APIs
REST APIs
Arthur De Magalhaes
 
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
Clean architectures with fast api pycones
Clean architectures with fast api pycones
Alvaro Del Castillo
 
Microservices and the Art of Taming the Dependency Hell Monster
Microservices and the Art of Taming the Dependency Hell Monster
C4Media
 
I Love APIs Europe 2015: Developer Sessions
I Love APIs Europe 2015: Developer Sessions
Apigee | Google Cloud
 
Building RESTful APIs
Building RESTful APIs
Silota Inc.
 
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
tatajebezad
 
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays
 
GraphQL Munich Meetup #1 - How We Use GraphQL At Commercetools
GraphQL Munich Meetup #1 - How We Use GraphQL At Commercetools
Nicola Molinari
 
Scaling with swagger
Scaling with swagger
Tony Tam
 
JSON API Specificiation
JSON API Specificiation
Wojciech Langiewicz
 
Apidays Paris 2023 - API design first: A case for a better language, Emmanu...
Apidays Paris 2023 - API design first: A case for a better language, Emmanu...
apidays
 
Api.pdf
Api.pdf
JitendraYadav351971
 
Always up to date, testable and maintainable documentation with OpenAPI
Always up to date, testable and maintainable documentation with OpenAPI
GOG.com dev team
 
REST in pieces
REST in pieces
sparkfabrik
 
[drupalday2017] - REST in pieces
[drupalday2017] - REST in pieces
DrupalDay
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
FastAPI - Rest Architecture - in english.pdf
FastAPI - Rest Architecture - in english.pdf
inigraha
 
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
FastAPI_with_Python_Presentation Fast Modern and Easy to Use
skpdbz
 
Clean architectures with fast api pycones
Clean architectures with fast api pycones
Alvaro Del Castillo
 
Microservices and the Art of Taming the Dependency Hell Monster
Microservices and the Art of Taming the Dependency Hell Monster
C4Media
 
I Love APIs Europe 2015: Developer Sessions
I Love APIs Europe 2015: Developer Sessions
Apigee | Google Cloud
 
Building RESTful APIs
Building RESTful APIs
Silota Inc.
 
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
Designing APIs with Swagger and OpenAPI 1st Edition Joshua S. Ponelat
tatajebezad
 
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays LIVE Paris - GraphQL meshes by Jens Neuse
apidays
 
GraphQL Munich Meetup #1 - How We Use GraphQL At Commercetools
GraphQL Munich Meetup #1 - How We Use GraphQL At Commercetools
Nicola Molinari
 
Scaling with swagger
Scaling with swagger
Tony Tam
 
Apidays Paris 2023 - API design first: A case for a better language, Emmanu...
Apidays Paris 2023 - API design first: A case for a better language, Emmanu...
apidays
 
Always up to date, testable and maintainable documentation with OpenAPI
Always up to date, testable and maintainable documentation with OpenAPI
GOG.com dev team
 
[drupalday2017] - REST in pieces
[drupalday2017] - REST in pieces
DrupalDay
 
Ad

More from Max Klymyshyn (20)

Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
LvivPy - Flask in details
LvivPy - Flask in details
Max Klymyshyn
 

Recently uploaded (20)

HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Which Hiring Management Tools Offer the Best ROI?
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Canva Pro Crack Free Download 2025-FREE LATEST
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
Key Challenges in Troubleshooting Customer On-Premise Applications
Key Challenges in Troubleshooting Customer On-Premise Applications
Tier1 app
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
ElectraSuite_Prsentation(online voting system).pptx
ElectraSuite_Prsentation(online voting system).pptx
mrsinankhan01
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
Simplify Task, Team, and Project Management with Orangescrum Work
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Which Hiring Management Tools Offer the Best ROI?
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 

PiterPy 2016: Parallelization, Aggregation and Validation of API in Python

  • 1. Parallelisation, aggregation and validation API with Python Max Klymyshyn CTO at CartFresh @maxmaxmaxmax
  • 2. ‣ 12+ years of experience, 7 years with Python, 6 with JS ‣ Was part of oDesk, Helios, 42cc. ‣ Co-organizer of PyCon Ukraine, KyivJS, Papers We Love ‣ CTO at CartFresh ‣ Challenging myself with english talk. It’s not my first language, bear with me About
  • 3. ‣ Grocery Delivery startup ‣ Operating as CartFresh (Boston, US) and ZAKAZ.UA (Kiev, Dnepropetrovsk, Kharkiv, Ukraine) ‣ Apache CouchDB, Apache Solr, Redis ‣ Heavy python on back-end CartFresh
  • 4. ‣ Quick overview ‣ Some abstract info about context ‣ Tools for Python Table of contents
  • 6. World is changing very quickly: ‣ Mobile apps ‣ Internet of Things ‣ Microservices ‣ Isomorphic apps Why API again?
  • 7. Good API is hard when all your stuff should work together well
  • 8. ‣ Validation ‣ Reusability ‣ Consistency ‣ Maintainability ‣ Scalability It’s challenging
  • 9. Good API makes it easier to develop a service
  • 11. ‣ API expresses a software component in terms of its operations, inputs, outputs, and underlying types ‣ API helps create reusable building blocks and communicate between system components ‣ It opens new opportunities to develop new systems based on your product Overview
  • 13. ‣ input – need to be validated for type correctness ‣ validation – input should be constrained by domain- specific business rules ‣ business logic – obviously most useful part of the system ‣ output – data model, serialised into specific format Moving parts
  • 14. API creation becomes trivial with good understanding and right tools All challenges are behind: how to make it simple, how to make it maintainable, how to keep API users updated
  • 15. Trends during the past few years
  • 16. ‣ RESTification ‣ Data Query Languages ‣ Microservices architecture Trends
  • 17. REST ‣ Unified interface to communication protocol between client and API ‣ Built on top of HTTP ‣ Simple
  • 18. Data Query Languages ‣ GraphQL ‣ Falcor ‣ Datalog ‣ Datomic etc.
  • 19. Data Query Languages Main point of DQL is to make declarative composition of queries to simple data structures and represent it as single data structure
  • 25. ‣ New layer of complexity in terms of input validation ‣ New unreliable layer (network) ‣ Additional protocol overhead ‣ Communication latency Seriously
  • 26. ‣ You’ll get a chance to improve each piece of code separately without breaking other part of the system (D&C!) ‣ You can split development of microservices between different dev teams ‣ You’ll get a lot of fun! But let’s be optimistic
  • 27. Tools
  • 28. ‣ SWAGGER – a simple representation of your RESTful API (OpenAPI initiative), FLEX for Python ‣ RESTful API Modelling Language – RAML ‣ APIDOC – a documentation from API annotations in your source code ‣ api-blueprint, RESTUnite, apiary etc. API Frameworks
  • 29. paths: /products: get: summary: Product Types description: | The Products endpoint returns information about the *Uber* products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order. parameters: - name: latitude in: query description: Latitude component of location. required: true type: number format: double - name: longitude in: query description: Longitude component of location. required: true type: number format: double tags: - Products responses: 200: description: An array of products schema: type: array items: $ref: '#/definitions/Product' Swagger spec example
  • 30. /products: uriParameters: displayName: Products description: A collection of products post: description: Create a product #Post body media type support #text/xml: !!null # media type text, xml support #application/json: !!null #media type json support body: application/json: schema: | { "$schema": "http://json-schema.org/draft-03/schema", "product": { "name": { "required": true, "type": "string" }, "description": { "required": true, "type": "string" } RAML spec example
  • 31. example: | { "product": { "id": "1", "name": "Product One", ... } } get: description: Get a list of products queryParameters: q: description: Search phrase to look for products type: string required: false responses: 200: body: application/json: #example: !include schema/product-list.json RAML spec example
  • 32. To prevent situation when documentation, client libraries, and source code get out of sync CLIENT #1 SERVER CLIENT #2
  • 33. ‣ Predefined input parameters + validation ‣ Predefined response schema (model) ‣ Query Language Aggregation
  • 34. GraphQL/Graphene import graphene import pprint data = [1, 2, 3, 4] class Query(graphene.ObjectType): hello = graphene.String() data = graphene.String() def resolve_data(self, args, info): return ",".join(map(str, data)) def resolve_hello(self, args, info): return 'World' schema = graphene.Schema(query=Query) result = schema.execute('{ hello, data }') pprint.pprint(result.data) # OrderedDict([('hello', u'World'), ('data', u'1,2,3,4')])
  • 35. GraphQL’s power comes from a simple idea —  instead of defining the structure of responses on the server, the flexibility is given to the client. GraphQL vs REST
  • 36. GraphQL/graphene allow us to use our beloved language for declaration of Model/API Schema: python GraphQL vs Swagger
  • 38. Tools: django-batch-requests [ { "method": "get", "url": "/sleep/?seconds=3" }, { "method": "get", "url": "/sleep/?seconds=3" } ]
  • 39. [ { "headers": { "Content-Type": "text/html; charset=utf-8", "batch_requests.duration": 3 }, "status_code": 200, "body": "Success!", "reason_phrase": "OK" }, { "headers": { "Content-Type": "text/html; charset=utf-8", "batch_requests.duration": 3 }, "status_code": 200, "body": "Success!", "reason_phrase": "OK" } ]
  • 41. ‣ End up with batched API interface ‣ Declarative input validation with trafaret ‣ Free schema (disadvantage) ‣ Very simple SQL-JOIN-like aggregation
  • 42. Params, validation, transformation @validate_args( _('Invalid request'), store_id=tr.String() >> pipe(unicode, unicode.strip), slugs=tr.List(tr.String() >> pipe(unicode, unicode.strip)), ean=tr.String | tr.Null, extended=tr.Bool | tr.Null, query=tr.String | tr.Null, facets=tr.List( tr.List(tr.String, min_length=2, max_length=2)) | tr.Null, sort=tr.String(allow_blank=True) | tr.Null, _optional=('extended', 'query', 'facets', 'sort', 'ean')) def resource_products(store, user, session, limit=None, offset=1, lang='en', args=None, **kwargs): pass
  • 43. [ "store.products", { store_id: Storage.first(“store").id, slugs: [options.slug], facets: options.facets || [], sort: options.sort || “" }, { offset: options.offset || 1, id: "catalog", join: [{ apply_as: "facets_base", on: ["slug", "slug"], request: { type: "store.facets", args: { store_id: "$request.[-2].args.store_id", slug: "$request.[-2].args.slugs|first" } } }, { apply_as: "category_tree", on: ["slug", "requested_slug"], request: { type: "store.department_tree", args: { store_id: "$request.[-2].args.store_id", slug: "$request.[-2].args.slugs|first" } } }] } ]