SlideShare una empresa de Scribd logo
1 de 38
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Introducing AWS Fargate - AWS Online Tech Talks
Introducing AWS Fargate - AWS Online Tech TalksIntroducing AWS Fargate - AWS Online Tech Talks
Introducing AWS Fargate - AWS Online Tech TalksAmazon Web Services
 
AngularJS - Présentation (french)
AngularJS - Présentation (french)AngularJS - Présentation (french)
AngularJS - Présentation (french)Yacine Rezgui
 
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...Amazon Web Services
 
iOS Modular Architecture with Tuist
iOS Modular Architecture with TuistiOS Modular Architecture with Tuist
iOS Modular Architecture with Tuist정민 안
 
Intro to AWS Developer Tools, featuring AWS CodeStar
Intro to AWS Developer Tools, featuring AWS CodeStarIntro to AWS Developer Tools, featuring AWS CodeStar
Intro to AWS Developer Tools, featuring AWS CodeStarAmazon Web Services
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
API first Design and Microservices
API first Design and MicroservicesAPI first Design and Microservices
API first Design and MicroservicesSven Bernhardt
 
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalk
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalkContinuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalk
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalkThomas Shaw
 
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar Series
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar SeriesContinuous Delivery with AWS Lambda - AWS April 2016 Webinar Series
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar SeriesAmazon Web Services
 
Angular vs React: Building modern SharePoint interfaces with SPFx
Angular vs React: Building modern SharePoint interfaces with SPFxAngular vs React: Building modern SharePoint interfaces with SPFx
Angular vs React: Building modern SharePoint interfaces with SPFxDimcho Tsanov
 
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...AWS Chicago
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development정민 안
 
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...Amazon Web Services
 
Automate Software Deployments on EC2 with AWS CodeDeploy
Automate Software Deployments on EC2 with AWS CodeDeployAutomate Software Deployments on EC2 with AWS CodeDeploy
Automate Software Deployments on EC2 with AWS CodeDeployAmazon Web Services
 
No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...
 No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ... No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...
No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...Amazon Web Services
 
Introduction to ansible galaxy
Introduction to ansible galaxyIntroduction to ansible galaxy
Introduction to ansible galaxyIvan Serdyuk
 

La actualidad más candente (20)

Introducing AWS Fargate - AWS Online Tech Talks
Introducing AWS Fargate - AWS Online Tech TalksIntroducing AWS Fargate - AWS Online Tech Talks
Introducing AWS Fargate - AWS Online Tech Talks
 
AngularJS - Présentation (french)
AngularJS - Présentation (french)AngularJS - Présentation (french)
AngularJS - Présentation (french)
 
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
Building API-Driven Microservices with Amazon API Gateway - AWS Online Tech T...
 
iOS Modular Architecture with Tuist
iOS Modular Architecture with TuistiOS Modular Architecture with Tuist
iOS Modular Architecture with Tuist
 
Intro to AWS Developer Tools, featuring AWS CodeStar
Intro to AWS Developer Tools, featuring AWS CodeStarIntro to AWS Developer Tools, featuring AWS CodeStar
Intro to AWS Developer Tools, featuring AWS CodeStar
 
AWS Cloud Watch
AWS Cloud WatchAWS Cloud Watch
AWS Cloud Watch
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Web Development In Oracle APEX
Web Development In Oracle APEXWeb Development In Oracle APEX
Web Development In Oracle APEX
 
API first Design and Microservices
API first Design and MicroservicesAPI first Design and Microservices
API first Design and Microservices
 
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalk
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalkContinuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalk
Continuous Delivery using AWS CodePipeline, AWS Lambda & AWS ElasticBeanstalk
 
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar Series
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar SeriesContinuous Delivery with AWS Lambda - AWS April 2016 Webinar Series
Continuous Delivery with AWS Lambda - AWS April 2016 Webinar Series
 
Angular vs React: Building modern SharePoint interfaces with SPFx
Angular vs React: Building modern SharePoint interfaces with SPFxAngular vs React: Building modern SharePoint interfaces with SPFx
Angular vs React: Building modern SharePoint interfaces with SPFx
 
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...
AWS Community Day 2022 Dhiraj Mahapatro_AWS Lambda under the hood _ Best Prac...
 
A Framework Driven Development
A Framework Driven DevelopmentA Framework Driven Development
A Framework Driven Development
 
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...
Use Elastic Beanstalk Blue/Green Deployment to Reduce Downtime & Risk (DEV330...
 
AWS CodeDeploy
AWS CodeDeployAWS CodeDeploy
AWS CodeDeploy
 
Automate Software Deployments on EC2 with AWS CodeDeploy
Automate Software Deployments on EC2 with AWS CodeDeployAutomate Software Deployments on EC2 with AWS CodeDeploy
Automate Software Deployments on EC2 with AWS CodeDeploy
 
No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...
 No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ... No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...
No Hassle NoSQL - Amazon DynamoDB & Amazon DocumentDB | AWS Summit Tel Aviv ...
 
Introduction to ansible galaxy
Introduction to ansible galaxyIntroduction to ansible galaxy
Introduction to ansible galaxy
 
Angular
AngularAngular
Angular
 

Destacado

Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOSMake School
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout OverviewMake School
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewMake School
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOSMake School
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C InteropMake School
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOSMake School
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application ArchitectureMake School
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core DataMake School
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOSMake School
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project InfrastructureMake School
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOSMake School
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in SwiftMake School
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOSMake School
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOSMake School
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOSMake School
 

Destacado (20)

Client Server Security with Flask and iOS
Client Server Security with Flask and iOSClient Server Security with Flask and iOS
Client Server Security with Flask and iOS
 
Make School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS DevelopmentMake School 2017 - Mastering iOS Development
Make School 2017 - Mastering iOS Development
 
iOS Layout Overview
iOS Layout OverviewiOS Layout Overview
iOS Layout Overview
 
Layout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection ViewLayout with Stack View, Table View, and Collection View
Layout with Stack View, Table View, and Collection View
 
Persistence on iOS
Persistence on iOSPersistence on iOS
Persistence on iOS
 
Swift Objective-C Interop
Swift Objective-C InteropSwift Objective-C Interop
Swift Objective-C Interop
 
Standard libraries on iOS
Standard libraries on iOSStandard libraries on iOS
Standard libraries on iOS
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Intro to iOS Application Architecture
Intro to iOS Application ArchitectureIntro to iOS Application Architecture
Intro to iOS Application Architecture
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Swift 2 intro
Swift 2 introSwift 2 intro
Swift 2 intro
 
Dependency Management on iOS
Dependency Management on iOSDependency Management on iOS
Dependency Management on iOS
 
Xcode Project Infrastructure
Xcode Project InfrastructureXcode Project Infrastructure
Xcode Project Infrastructure
 
Client Server Synchronization iOS
Client Server Synchronization iOSClient Server Synchronization iOS
Client Server Synchronization iOS
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
 
Localization and Accessibility on iOS
Localization and Accessibility on iOSLocalization and Accessibility on iOS
Localization and Accessibility on iOS
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOS
 
Memory Management on iOS
Memory Management on iOSMemory Management on iOS
Memory Management on iOS
 

Similar a Building a Flask Server API with MongoDB and TDD

Greenfield Development with CQRS
Greenfield Development with CQRSGreenfield Development with CQRS
Greenfield Development with CQRSDavid Hoerster
 
Modern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaModern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaLucas Jellema
 
How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?AmeliaWong21
 
4. aws enterprise summit seoul 기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park
4. aws enterprise summit seoul   기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park4. aws enterprise summit seoul   기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park
4. aws enterprise summit seoul 기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas parkAmazon Web Services Korea
 
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DB
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DBBuilding event-driven Serverless Apps with Azure Functions and Azure Cosmos DB
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DBMicrosoft Tech Community
 
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client ManagerDrupalDay
 
Cics web interface new
Cics web interface newCics web interface new
Cics web interface newBalmukundb
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?AmeliaWong21
 
The Story of How an Oracle Classic Stronghold successfully embraced SOA
The Story of How an Oracle Classic Stronghold successfully embraced SOAThe Story of How an Oracle Classic Stronghold successfully embraced SOA
The Story of How an Oracle Classic Stronghold successfully embraced SOALucas Jellema
 
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...Jim McKeeth
 
MSFT Dumaguete 061616 - Building High Performance Apps
MSFT Dumaguete 061616 - Building High Performance AppsMSFT Dumaguete 061616 - Building High Performance Apps
MSFT Dumaguete 061616 - Building High Performance AppsMarc Obaldo
 
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...Edureka!
 
Wisconsin .NET UG - Windows Azure
Wisconsin .NET UG - Windows AzureWisconsin .NET UG - Windows Azure
Wisconsin .NET UG - Windows AzureWade Wegner
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Gaurav Bhardwaj
 
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Amazon Web Services
 

Similar a Building a Flask Server API with MongoDB and TDD (20)

Greenfield Development with CQRS
Greenfield Development with CQRSGreenfield Development with CQRS
Greenfield Development with CQRS
 
EVOLVE'14 | Enhance | Anshul Chhabra & Akhil Aggrawal | Cisco - AEM High Avai...
EVOLVE'14 | Enhance | Anshul Chhabra & Akhil Aggrawal | Cisco - AEM High Avai...EVOLVE'14 | Enhance | Anshul Chhabra & Akhil Aggrawal | Cisco - AEM High Avai...
EVOLVE'14 | Enhance | Anshul Chhabra & Akhil Aggrawal | Cisco - AEM High Avai...
 
Modern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas JellemaModern Database Development Oow2008 Lucas Jellema
Modern Database Development Oow2008 Lucas Jellema
 
Fm 2
Fm 2Fm 2
Fm 2
 
How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?
 
4. aws enterprise summit seoul 기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park
4. aws enterprise summit seoul   기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park4. aws enterprise summit seoul   기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park
4. aws enterprise summit seoul 기존 엔터프라이즈 it 솔루션 클라우드로 이전하기 - thomas park
 
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DB
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DBBuilding event-driven Serverless Apps with Azure Functions and Azure Cosmos DB
Building event-driven Serverless Apps with Azure Functions and Azure Cosmos DB
 
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
 
Cics web interface new
Cics web interface newCics web interface new
Cics web interface new
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
02 api gateway
02 api gateway02 api gateway
02 api gateway
 
How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?How to use Informatica Power Center as a RESTful Web Service Client?
How to use Informatica Power Center as a RESTful Web Service Client?
 
The Story of How an Oracle Classic Stronghold successfully embraced SOA
The Story of How an Oracle Classic Stronghold successfully embraced SOAThe Story of How an Oracle Classic Stronghold successfully embraced SOA
The Story of How an Oracle Classic Stronghold successfully embraced SOA
 
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...
Accessing REST & Backend as a Service (BaaS) - Developer Direct - Mobile Summ...
 
MSFT Dumaguete 061616 - Building High Performance Apps
MSFT Dumaguete 061616 - Building High Performance AppsMSFT Dumaguete 061616 - Building High Performance Apps
MSFT Dumaguete 061616 - Building High Performance Apps
 
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...
AWS Data Pipeline Tutorial | AWS Tutorial For Beginners | AWS Certification T...
 
Wisconsin .NET UG - Windows Azure
Wisconsin .NET UG - Windows AzureWisconsin .NET UG - Windows Azure
Wisconsin .NET UG - Windows Azure
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
 
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
 

Último

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Último (20)

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Building a Flask Server API with MongoDB and TDD

  • 1.
  • 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