SlideShare a Scribd company logo
Building a Backend with Flask
BUILDING A SERVER WITH
FLASK
AGENDA
Client-Server Communication
Building a Custom Backend
Flask / MongoDB
Defining a Server API
Development Technique
CLIENT-SERVER
COMMUNICATION
CLIENT-SERVER
COMMUNICATION
1. Serialization
2. Network Requests
SERIALIZATION
Transforming in-memory object graphs into a
linear sequence of data that can be stored on
disk or sent over a network
SERIALIZATION
User User
Product Product
Product
Product
Object Graph Serialized Document
{
UserID: 934235,
Username: "Ben-G",
Purchases:
[
{
ProductID: 1278123,
Price: 99,
Name: "Apple TV"
}
],
[
{
ProductID: 7238483,
Price: 299,
Name: "Kitchen Set"
}
],
}
Serialization
SERVER ARCHITECTURE &
REQUEST LIFECYCLE
CLASSIC 3-TIER ARCHITECTURE
Client is a “thin client” only taking care of
representation
The actual logic of the application is
implemented on the server
Representation
Business Logic
Persistence
Client
Server
DB
Network Requests
Insert, Select, Update,
Delete
MODERN 3-TIER ARCHITECTURE
Client
Server
DB
HTTP Requests /
Responses
Insert, Select, Update,
Delete
Client has become a “fat client”, in many cases
implementing a significant amount of business logic
Amount of business logic on the server can vary
In Apps that use the Parse Framework, for example,
the Backend only acts as a proxy for the DB
In contrast Twitter has a huge amount of server
logic and less logic on the client
Business Logic
Representation
Business Logic
Persistence
Client
Server
DB
getUsers:
HTTP Request
GET http://myApp/Users
function getUsers {
return db.user.find()
}
DB Request
User1
User2
User3
User4
HTTP Response
[
{
username: “Test1”,
age: 20
},
{
username: “Test2”,
age: 23
},
…
]
User
User
User
User
Parse into Objects
Client
DB
1
2
3
4
5
67
CLIENT-

SERVER

REQUEST
CYCLE
ANATOMY OF AN HTTP REQUEST [1]
HTTP Method
URI
Header Fields
(Authorization, Content-Type)
Body
BUILDING A CUSTOM
BACKEND
WHY?
Education: Writing a custom backend will help
you understand client server communication
Flexibility: Frameworks, such as Parse, don’t
provide the full flexibility of custom solutions, in
many cases it will be necessary to write a custom
backend
HOW?
Flask: a simple framework for web applications
written in python
MongoDB: a document based database
RELATIONAL VS DOCUMENT
BASED DB
BRIEF OVERVIEW
RELATIONAL DB
Strongly denormalized data model → low
redundancy
Besides IDs we don’t have redundant information,
e.g. product name is only stored in one place
If we have a username and want to get the name
of a purchased product we need to JOIN all three
tables
UsernameUserID
USER
Ben-G934235
USER_PURCHASES
ProductIDUserID
1278123934235
7238483934235
232133123233
123233 Daniela
PRODUCT
PriceProductID
991278123
2997238483
679123233
Name
Apple TV
Kitchen Set
Expensive Shoes
RELATIONAL DB
Strict Schema → Application knows exact format of data
stored in DB
Normalized model makes writes easier. Information only
needs to be updated in one place
Frequent JOIN operations are expensive
Strict Schema → Even simple changes need schema
migration
DOCUMENT BASED DB
Mostly strongly denormalized, this means a lot of
redundant information is stored
E.g.: Product Information could be stored directly in
the purchase record, product information is stored
with every single purchase
Faster reading, slower writing
MongoDB has a flexible schema, that means fields
can be added to / omitted from documents
{
UserID: 934235,
Username: "Ben-G",
Purchases:
[
{
ProductID: 1278123,
Price: 99,
Name: "Apple TV"
}
],
[
{
ProductID: 7238483,
Price: 299,
Name: "Kitchen Set"
}
],
}
DOCUMENT BASED DB
Top level hierarchy consists of
collections
Collections contain documents
DB
User
User Collection
User
User User
Location
Location Collection
Location
Location Location
DOCUMENT BASED DB
No Schema → It’s easy to change the data model of an
existing application without needing a migration
Denormalized model makes reads faster, there’s no need to
join different documents
Write operations can be expensive as denormalized data
needs to be updated in multiple places
No Schema → You need to handle different schema versions
on an application level
FLASK
FLASK
A python framework for building web servers
Allows to map different HTTP requests to python
functions
Provides many libraries that we’ll use to speed
up development
DEFINING A SERVER API
DEFINING A SERVER API
Many different ways to structure a backend
server
Will use the one that is currently most common:
RESTful Web Services
RESTFUL WEB SERVICES
Server does not store state of client connection
between requests, all the information necessary
to service the request is provided by client.
There are no server-side sessions.
Web Service is structured based on resources
e.g. a User resource, a Product resource
RESTFUL WEB SERVICES
Each request consists of:
URL - identifies the affected resource
HTTP Method (GET, PUT, etc.) - defines the action
on the resource
Request Body - can contain additional information
on how resource should be affected
RESTFUL WEB SERVICE EXAMPLE
Based on: http://en.wikipedia.org/wiki/Representational_state_transfer
Resource GET PUT POST DELETE
Collection URI, e.g.


http://planly.com/trips
Return list of
trips with
details or list of
trip URIs
Replace entire
collection with
another
collection
Create a new
entry in the
collection
Delete the
entire
collection
Element URI, e.g.


http://planly.com/trips/18
Return a
representation
of specified
item
Replace
specified item
-
Delete the
specified item
DEVELOPMENT TECHNIQUE
TDD
TDD (Test Driven Development) is an approach to
Software Development in which development
starts by writing automated tests before writing
application code
Tests specify the behavior of the application
TDD
Development Cycle with TDD:
1. Write a test for a software feature
2. Run test - test will fail
3. Implement feature
4. Run test - test should succeed
5. Refactor code for implementation
6. Run test - test should succeed
This is often referred to as Red → Green → Refactor
TDD - EXAMPLE TEST CASE
def test_incorrect_credentials(self):
response = self.app.get('/user/',
headers=self.generate_auth_header(
'wrongusername', 'andpassword')
)
self.assertEqual(response.status_code, 401)
SUMMARY
SUMMARY
Many Applications (including ours) use a 3-Tier architecture with a
lightweight server
We are going to implement a server with flask that uses the
document based DBMS MongoDB
We are going to implement a RESTful Web Service that will be
consumed by our iOS application
We will implement the server with TDD, writing tests first and code
second
GETTING STARTED
GETTING STARTED
The dashboard contains a writeup on how to
setup your development environment
It also contains a starter project for your backend
server
REFERENCES
REFERENCES
[1] HTTP Header Field Definitions

More Related Content

What's hot (11)

PPS
أنواع الهمزات
Said Ayad
 
PDF
給你一個使用 Laravel 的理由
Shengyou Fan
 
DOC
الأسرار العلية في مناقب الشاذلى
Free Interactive Islamic College, All in One Open Traditional Certificate www.Muhammad.com
 
PDF
(16) موسى عليه السلام
صوت لا يصمت رامه أبوالرُّب
 
PDF
今更聞けない? Androidのテストのいろは
Hiroshi Kikuchi
 
PPTX
Let's play with adf 3.0
Eugenio Romano
 
PDF
بعض قواعد الإملاء الهامة Ast school
AST-School
 
PPTX
Google drive presentation
shaikha90
 
PDF
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
HackIT Ukraine
 
أنواع الهمزات
Said Ayad
 
給你一個使用 Laravel 的理由
Shengyou Fan
 
الأسرار العلية في مناقب الشاذلى
Free Interactive Islamic College, All in One Open Traditional Certificate www.Muhammad.com
 
(16) موسى عليه السلام
صوت لا يصمت رامه أبوالرُّب
 
今更聞けない? Androidのテストのいろは
Hiroshi Kikuchi
 
Let's play with adf 3.0
Eugenio Romano
 
بعض قواعد الإملاء الهامة Ast school
AST-School
 
Google drive presentation
shaikha90
 
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
HackIT Ukraine
 

Viewers also liked (20)

PDF
Client Server Security with Flask and iOS
Make School
 
PDF
Make School 2017 - Mastering iOS Development
Make School
 
PDF
iOS Layout Overview
Make School
 
PDF
Layout with Stack View, Table View, and Collection View
Make School
 
PDF
Persistence on iOS
Make School
 
PDF
Swift Objective-C Interop
Make School
 
PDF
Standard libraries on iOS
Make School
 
PDF
Intro to Core Data
Make School
 
PDF
Multithreading on iOS
Make School
 
PDF
Intro to iOS Application Architecture
Make School
 
PDF
Advanced Core Data
Make School
 
PDF
Client Server Communication on iOS
Make School
 
PDF
Swift 2 intro
Make School
 
PDF
Dependency Management on iOS
Make School
 
PDF
Xcode Project Infrastructure
Make School
 
PDF
Client Server Synchronization iOS
Make School
 
PDF
Error Handling in Swift
Make School
 
PDF
Localization and Accessibility on iOS
Make School
 
PDF
Automated Testing on iOS
Make School
 
PDF
Memory Management on iOS
Make School
 
Client Server Security with Flask and iOS
Make School
 
Make School 2017 - Mastering iOS Development
Make School
 
iOS Layout Overview
Make School
 
Layout with Stack View, Table View, and Collection View
Make School
 
Persistence on iOS
Make School
 
Swift Objective-C Interop
Make School
 
Standard libraries on iOS
Make School
 
Intro to Core Data
Make School
 
Multithreading on iOS
Make School
 
Intro to iOS Application Architecture
Make School
 
Advanced Core Data
Make School
 
Client Server Communication on iOS
Make School
 
Swift 2 intro
Make School
 
Dependency Management on iOS
Make School
 
Xcode Project Infrastructure
Make School
 
Client Server Synchronization iOS
Make School
 
Error Handling in Swift
Make School
 
Localization and Accessibility on iOS
Make School
 
Automated Testing on iOS
Make School
 
Memory Management on iOS
Make School
 
Ad

Similar to Building a Backend with Flask (20)

PDF
MongoDB.local Berlin: App development in a Serverless World
MongoDB
 
PPTX
Webinar: Build an Application Series - Session 2 - Getting Started
MongoDB
 
PDF
Designing your API Server for mobile apps
Mugunth Kumar
 
KEY
Couchdb: No SQL? No driver? No problem
delagoya
 
KEY
CouchDB : More Couch
delagoya
 
PPTX
Building Your First App with MongoDB
MongoDB
 
PPTX
S01 e01 schema-design
MongoDB
 
PDF
REST Web API with MongoDB
MongoDB
 
PPTX
Mtn view sql server nov 2014
EspressoLogic
 
KEY
Building a Cross Channel Content Delivery Platform with MongoDB
MongoDB
 
PPTX
A great api is hard to find
Dan Diephouse
 
PPT
Java Script Based Client Server Webapps 2
kriszyp
 
PDF
MongoDB: a gentle, friendly overview
Antonio Pintus
 
PPTX
Webinar: Getting Started with MongoDB - Back to Basics
MongoDB
 
PPTX
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Tim Vaillancourt
 
PPTX
Visualizing Software Architecture and visualizations
collinskipkosgei2003
 
PPTX
Iphone client-server app with Rails backend (v3)
Sujee Maniyam
 
PPTX
Couchbase Overview - Monterey Bay Information Technologists Meetup 02.15.17
Aaron Benton
 
KEY
Optimize drupal using mongo db
Vladimir Ilic
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB
 
Webinar: Build an Application Series - Session 2 - Getting Started
MongoDB
 
Designing your API Server for mobile apps
Mugunth Kumar
 
Couchdb: No SQL? No driver? No problem
delagoya
 
CouchDB : More Couch
delagoya
 
Building Your First App with MongoDB
MongoDB
 
S01 e01 schema-design
MongoDB
 
REST Web API with MongoDB
MongoDB
 
Mtn view sql server nov 2014
EspressoLogic
 
Building a Cross Channel Content Delivery Platform with MongoDB
MongoDB
 
A great api is hard to find
Dan Diephouse
 
Java Script Based Client Server Webapps 2
kriszyp
 
MongoDB: a gentle, friendly overview
Antonio Pintus
 
Webinar: Getting Started with MongoDB - Back to Basics
MongoDB
 
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Tim Vaillancourt
 
Visualizing Software Architecture and visualizations
collinskipkosgei2003
 
Iphone client-server app with Rails backend (v3)
Sujee Maniyam
 
Couchbase Overview - Monterey Bay Information Technologists Meetup 02.15.17
Aaron Benton
 
Optimize drupal using mongo db
Vladimir Ilic
 
Ad

Recently uploaded (20)

PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Tally software_Introduction_Presentation
AditiBansal54083
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 

Building a Backend with Flask

  • 2. BUILDING A SERVER WITH FLASK
  • 3. AGENDA Client-Server Communication Building a Custom Backend Flask / MongoDB Defining a Server API Development Technique
  • 6. SERIALIZATION Transforming in-memory object graphs into a linear sequence of data that can be stored on disk or sent over a network
  • 7. SERIALIZATION User User Product Product Product Product Object Graph Serialized Document { UserID: 934235, Username: "Ben-G", Purchases: [ { ProductID: 1278123, Price: 99, Name: "Apple TV" } ], [ { ProductID: 7238483, Price: 299, Name: "Kitchen Set" } ], } Serialization
  • 9. CLASSIC 3-TIER ARCHITECTURE Client is a “thin client” only taking care of representation The actual logic of the application is implemented on the server Representation Business Logic Persistence Client Server DB Network Requests Insert, Select, Update, Delete
  • 10. MODERN 3-TIER ARCHITECTURE Client Server DB HTTP Requests / Responses Insert, Select, Update, Delete Client has become a “fat client”, in many cases implementing a significant amount of business logic Amount of business logic on the server can vary In Apps that use the Parse Framework, for example, the Backend only acts as a proxy for the DB In contrast Twitter has a huge amount of server logic and less logic on the client Business Logic Representation Business Logic Persistence
  • 11. Client Server DB getUsers: HTTP Request GET http://myApp/Users function getUsers { return db.user.find() } DB Request User1 User2 User3 User4 HTTP Response [ { username: “Test1”, age: 20 }, { username: “Test2”, age: 23 }, … ] User User User User Parse into Objects Client DB 1 2 3 4 5 67 CLIENT-
 SERVER
 REQUEST CYCLE
  • 12. ANATOMY OF AN HTTP REQUEST [1] HTTP Method URI Header Fields (Authorization, Content-Type) Body
  • 14. WHY? Education: Writing a custom backend will help you understand client server communication Flexibility: Frameworks, such as Parse, don’t provide the full flexibility of custom solutions, in many cases it will be necessary to write a custom backend
  • 15. HOW? Flask: a simple framework for web applications written in python MongoDB: a document based database
  • 16. RELATIONAL VS DOCUMENT BASED DB BRIEF OVERVIEW
  • 17. RELATIONAL DB Strongly denormalized data model → low redundancy Besides IDs we don’t have redundant information, e.g. product name is only stored in one place If we have a username and want to get the name of a purchased product we need to JOIN all three tables UsernameUserID USER Ben-G934235 USER_PURCHASES ProductIDUserID 1278123934235 7238483934235 232133123233 123233 Daniela PRODUCT PriceProductID 991278123 2997238483 679123233 Name Apple TV Kitchen Set Expensive Shoes
  • 18. RELATIONAL DB Strict Schema → Application knows exact format of data stored in DB Normalized model makes writes easier. Information only needs to be updated in one place Frequent JOIN operations are expensive Strict Schema → Even simple changes need schema migration
  • 19. DOCUMENT BASED DB Mostly strongly denormalized, this means a lot of redundant information is stored E.g.: Product Information could be stored directly in the purchase record, product information is stored with every single purchase Faster reading, slower writing MongoDB has a flexible schema, that means fields can be added to / omitted from documents { UserID: 934235, Username: "Ben-G", Purchases: [ { ProductID: 1278123, Price: 99, Name: "Apple TV" } ], [ { ProductID: 7238483, Price: 299, Name: "Kitchen Set" } ], }
  • 20. DOCUMENT BASED DB Top level hierarchy consists of collections Collections contain documents DB User User Collection User User User Location Location Collection Location Location Location
  • 21. DOCUMENT BASED DB No Schema → It’s easy to change the data model of an existing application without needing a migration Denormalized model makes reads faster, there’s no need to join different documents Write operations can be expensive as denormalized data needs to be updated in multiple places No Schema → You need to handle different schema versions on an application level
  • 22. FLASK
  • 23. FLASK A python framework for building web servers Allows to map different HTTP requests to python functions Provides many libraries that we’ll use to speed up development
  • 25. DEFINING A SERVER API Many different ways to structure a backend server Will use the one that is currently most common: RESTful Web Services
  • 26. RESTFUL WEB SERVICES Server does not store state of client connection between requests, all the information necessary to service the request is provided by client. There are no server-side sessions. Web Service is structured based on resources e.g. a User resource, a Product resource
  • 27. RESTFUL WEB SERVICES Each request consists of: URL - identifies the affected resource HTTP Method (GET, PUT, etc.) - defines the action on the resource Request Body - can contain additional information on how resource should be affected
  • 28. RESTFUL WEB SERVICE EXAMPLE Based on: http://en.wikipedia.org/wiki/Representational_state_transfer Resource GET PUT POST DELETE Collection URI, e.g. 
 http://planly.com/trips Return list of trips with details or list of trip URIs Replace entire collection with another collection Create a new entry in the collection Delete the entire collection Element URI, e.g. 
 http://planly.com/trips/18 Return a representation of specified item Replace specified item - Delete the specified item
  • 30. TDD TDD (Test Driven Development) is an approach to Software Development in which development starts by writing automated tests before writing application code Tests specify the behavior of the application
  • 31. TDD Development Cycle with TDD: 1. Write a test for a software feature 2. Run test - test will fail 3. Implement feature 4. Run test - test should succeed 5. Refactor code for implementation 6. Run test - test should succeed This is often referred to as Red → Green → Refactor
  • 32. TDD - EXAMPLE TEST CASE def test_incorrect_credentials(self): response = self.app.get('/user/', headers=self.generate_auth_header( 'wrongusername', 'andpassword') ) self.assertEqual(response.status_code, 401)
  • 34. SUMMARY Many Applications (including ours) use a 3-Tier architecture with a lightweight server We are going to implement a server with flask that uses the document based DBMS MongoDB We are going to implement a RESTful Web Service that will be consumed by our iOS application We will implement the server with TDD, writing tests first and code second
  • 36. GETTING STARTED The dashboard contains a writeup on how to setup your development environment It also contains a starter project for your backend server
  • 38. REFERENCES [1] HTTP Header Field Definitions