SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
FAST REST APIS DEVELOPMENT

                        WITH   MONGODB


Pablo Enfedaque Vidal

@pablitoev56
WHO?
•  Pablo Enfedaque


   •  Computers Engineer


   •  Tech Lead and R&D software engineer at Telefonica Digital


   •  Working with MongoDB for some years.
TELEFONICA DIGITAL. WHAT?
•  Telefonica


   •  Fifth largest telecommunications company in the world


   •  Operations in Europe (7 countries), the United States and
      Latin America (15 countries)


   •  Movistar, O2, Vivo, Terra, Tuenti, Jahjah, Tokbox,
      everything.me, Open Web Device…
TELEFONICA DIGITAL. WHAT?
•  Telefonica Digital


    •  Web and mobile digital contents and services division


    •  Product Development and Innovation unit
        •  Products & services development, research, technology
           strategy, user experience, deployment & operations…


        •  Around 70 different on going projects
OUR PROJECTS
•  Full product development, with life cycle and several deployments
    •  20 people team, 1 year or more


•  Pilot or small product to be deployed in a certain environment
    •  6 people team, 6 months


•  Seedbed or proof of concept to be run with reduced set of users
    •  3 people team, 3 months


•  Ten Fridays open exploratory project to work on your ideas
    •  2 people team, 10 days (consecutive Fridays)
SO…



      FAST DEVELOPMENT IS
      REALLY   CRUCIAL FOR US
HOW TO SPEED UP OUR DEVELOPMENTS?
•  Agile methodologies


•  Lean startup


•  eXtreme Programming


•  Continuous Integration


•  …
HOW TO SPEED UP OUR DEVELOPMENTS?



              CHOOSE THE
      RIGHT TECHNOLOGY
                (AT FIRST)
¿ RIGHT TECHNOLOGY ?
THE RIGHT TECHNOLOGY
•  Faster development with Dynamic Languages


   •  3x


   •  4x


   •  10x
THE RIGHT TECHNOLOGY

   THE SAME CAN BE STATED FOR
  •  3x
               MONGODB
  •  4x


  •  10x
THE RIGHT TECHNOLOGY
•  Several times faster development with Dynamic Languages


•  Several times faster development with MongoDB




         AND BOTH TOGETHER IS A

                        WIN WIN
WHY? HOW?


LET’S SEE SOME EXAMPLES
ONLY DYNAMIC LANGUAGES?
JAVA VERSION
public int[] getDims() {	
          	if (this.dims != null) {	
          	                	return this.dims;	
          	}	
          	BasicDBObject query = new BasicDBObject();	
          	query.put("_id", "ctxt_dimensions");	
          	DBObject setup = setup_coll.findOne(query);	
          	BasicDBList dbl = (BasicDBList)setup.get("dims");	
          	this.dims = new int[dbl.size() + 2];	
          	BasicDBObject users_counter_ref = new BasicDBObject("_id", users_coll_name);	
          	BasicDBObject apps_counter_ref = new BasicDBObject("_id", apps_coll_name);	
          	dims[0] = (Integer)counters_coll.findOne(users_counter_ref).get("value") + 1;	
          	dims[1] = (Integer)counters_coll.findOne(apps_counter_ref).get("value") + 1;	
          	for (int i=0; i<dbl.size(); i++) {	
          	          dims[i + 2] = (Integer)dbl.get(i);	
          	     }	
          	return dims;	
}
PYTHON VERSION
def get_dims(self):	
    ud = self.counters_coll.find_one({'_id': 'users'})['value']	
    ad = self.counters_coll.find_one({'_id': 'applications'})['value']	
    res = [ud, ad]	
    res.extend(self.setup_coll.find_one({}, {'dims': 1})['dims'])	
    return res	




                      IT’S UP TO YOU…
THE RIGHT TECHNOLOGY
LET’S PLAY TO SPOT THE
     DIFFERENCES
EXAMPLE: SPEAKER JSON
{
    "name": "Pablo Enfedaque",
    "company": "Telefonica Digital",
    "accepted": true,
    "registration_date": "2012-03-15T14:35:05",
    "num_talks": 1,
    ”votes": 4,
    "email": "pev@td.com"
}
EXAMPLE: DECODED JSON (PYTHON)
{
    "name": "Pablo Enfedaque",
    "company": "Telefonica Digital",
    "accepted": True,
    "registration_date": datetime(2012, 3, 15, 14, 35, 5),
    "num_talks": 1,
    ”votes": 4,
    "email": "pev@td.com"
}
EXAMPLE: MONGODB BSON
{
    "name": "Pablo Enfedaque",
    "company": "Telefonica Digital",
    "accepted": true,
    "registration_date": ISODate("2012-03-15T14:35:05Z"),
    "num_talks": 1,
    ”votes": 4,
    "email": "pev@td.com",
    ”_id": ObjectId("5142d08c5db1362abc2d208b”)
}
LOOKS PRETTY
STRAIGHT FORWARD,
      RIGHT?
SPEAKER CREATION
decoded_input = json.loads(input_json)	
decoded_input['registration_date'] =
datetime.strptime(decoded_input['registration_date'], "%Y-%m-%dT%H:%M:
%S”)	
return dbconn['speakers'].insert(decoded_input)	
	
> ObjectId('5142d2845db1362bb3155322')
SPEAKER RETRIEVAL
retrieved = dbconn['speakers'].find_one({'name': 'Pablo'}, {'_id': 0})	
retrieved['registration_date'] =
retrieved['registration_date'].strftime("%Y-%m-%dT%H:%M:%S")	
return retrieved
IT IS REALLY
STRAIGHT FORWARD!
WHAT IF WE WANT TO
CHANGE SPEAKERS DATA?
EXAMPLE: SPEAKER JSON
{
    "name": "Pablo Enfedaque",
    "company": "Telefonica Digital",
    "position": "R&D SW Engineer",
    "accepted": true,
    "registration_date": "2012-03-15T14:35:05",
    "num_talks": 1,
    ”votes": 4.3,  WAS AN INTEGER
    "email": "pev@td.com"
}
SPEAKER CREATION
decoded_input = json.loads(input_json)	
decoded_input['registration_date'] =
datetime.strptime(decoded_input['registration_date'], "%Y-%m-%dT%H:%M:
%S”)	
return dbconn['speakers'].insert(decoded_input)	




SPEAKER RETRIEVAL
retrieved = dbconn['speakers'].find_one({'name': 'Pablo'}, {'_id': 0})	
retrieved['registration_date'] =
retrieved['registration_date'].strftime("%Y-%m-%dT%H:%M:%S")	


             0 LINES CHANGED
return retrieved
INPUT VALIDATION NEEDED?
SPEAKER VALIDATION
from rest_framework import serializers	
class SpeakerSerializer(serializers.Serializer):	
    name = serializers.CharField(max_length=150)	
    company = serializers.CharField(max_length=150)	
    position = serializers.CharField(required=False)	
    accepted = serializers.BooleanField()	
    registration_date = serializers.DateTimeField()	
    num_talks = serializers.IntegerField()	
    votes = serializers.FloatField()	
    email = serializers.EmailField(max_length=150)	
    def restore_object(self, attrs, instance=None):	
        return attrs
SPEAKER CREATION
decoded_input = json.loads(input_json)	
serializer = SpeakerSerializer(decoded_input)	
print dbconn['speakers'].insert(serializer.object)	




SPEAKER RETRIEVAL
retrieved = dbconn['speakers'].find_one({'name': 'Pablo'})	
serializer = SpeakerSerializer(retrieved)	
return serializer.object
DON’T LIKE TO WORK WITH
DICTIONARIES / HASHES?
CUSTOMISE ATTRIBUTES ACCESS
class AttrDict(dict):	
    def __getattr__(self, name):	
        try:	
            return super(AttrDict, self).__getitem__(name)	
        except KeyError, e:	
            raise AttributeError(e)	
	
    def __setattr__(self, name, value):	
        if name in self:	
            super(AttrDict, self).__setitem__(name, value)	
        else:	
            super(AttrDict, self).__setattr__(name, value)
USE DICTIONARIES AS OBJECTS
decoded_input = json.loads(input_json)	
serializer = SpeakerSerializer(decoded_input)	
speaker_obj = AttrDict(serializer.object)	
print speaker_obj.company	
print speaker_obj['position']	
	
> Telefonica Digital	
R&D SW Engineer
USE AN ORM?
NO
OBJECT-RELATIONAL MAPPER


 NO RELATIONAL  NO ORM
         NEEDED
CONCLUSIONS
CONCLUSIONS
•    MongoDB + dynamic languages = fastest development speed
      •  14 months project with Oracle à 3 months project with MongoDB


•    REST API best practices
      •  Use JSON
      •  Use dictionaries / hashes
          •  Access dictionaries as objects
      •  No relational model à no ORM
          •  No other mappers
      •  Use decorators to handle AutoReconnect

Mais conteúdo relacionado

Mais procurados

FleetDB A Schema-Free Database in Clojure
FleetDB A Schema-Free Database in ClojureFleetDB A Schema-Free Database in Clojure
FleetDB A Schema-Free Database in Clojure
elliando dias
 
FleetDB: A Schema-Free Database in Clojure
FleetDB: A Schema-Free Database in ClojureFleetDB: A Schema-Free Database in Clojure
FleetDB: A Schema-Free Database in Clojure
Mark McGranaghan
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
GR8Conf
 
Improving RDF Search Performance with Lucene and SIREN
Improving RDF Search Performance with Lucene and SIRENImproving RDF Search Performance with Lucene and SIREN
Improving RDF Search Performance with Lucene and SIREN
Mike Hugo
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 
Appengine Java Night #2b
Appengine Java Night #2bAppengine Java Night #2b
Appengine Java Night #2b
Shinichi Ogawa
 

Mais procurados (20)

greenDAO
greenDAOgreenDAO
greenDAO
 
FleetDB A Schema-Free Database in Clojure
FleetDB A Schema-Free Database in ClojureFleetDB A Schema-Free Database in Clojure
FleetDB A Schema-Free Database in Clojure
 
FleetDB: A Schema-Free Database in Clojure
FleetDB: A Schema-Free Database in ClojureFleetDB: A Schema-Free Database in Clojure
FleetDB: A Schema-Free Database in Clojure
 
Testing javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjsTesting javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjs
 
Testing javascriptwithjasmine ddd-sydney
Testing javascriptwithjasmine ddd-sydneyTesting javascriptwithjasmine ddd-sydney
Testing javascriptwithjasmine ddd-sydney
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Improving RDF Search Performance with Lucene and SIREN
Improving RDF Search Performance with Lucene and SIRENImproving RDF Search Performance with Lucene and SIREN
Improving RDF Search Performance with Lucene and SIREN
 
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
NLP on a Billion Documents: Scalable Machine Learning with Apache SparkNLP on a Billion Documents: Scalable Machine Learning with Apache Spark
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
 
C# 7
C# 7C# 7
C# 7
 
Comparing 30 MongoDB operations with Oracle SQL statements
Comparing 30 MongoDB operations with Oracle SQL statementsComparing 30 MongoDB operations with Oracle SQL statements
Comparing 30 MongoDB operations with Oracle SQL statements
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
GeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with GroovyGeeCON Prague 2014 - Metaprogramming with Groovy
GeeCON Prague 2014 - Metaprogramming with Groovy
 
[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)[2019-07] GraphQL in depth (serverside)
[2019-07] GraphQL in depth (serverside)
 
Building DSLs with Groovy
Building DSLs with GroovyBuilding DSLs with Groovy
Building DSLs with Groovy
 
Appengine Java Night #2b
Appengine Java Night #2bAppengine Java Night #2b
Appengine Java Night #2b
 

Semelhante a Fast REST APIs Development with MongoDB

Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Victor Rentea
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
Sven Haiges
 
Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.
Ravi Teja
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
Paulo Gandra de Sousa
 

Semelhante a Fast REST APIs Development with MongoDB (20)

Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
How to leverage what's new in MongoDB 3.6
How to leverage what's new in MongoDB 3.6How to leverage what's new in MongoDB 3.6
How to leverage what's new in MongoDB 3.6
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
TDC2018SP | Trilha .Net - Novidades do C# 7 e 8
 
Building Services With gRPC, Docker and Go
Building Services With gRPC, Docker and GoBuilding Services With gRPC, Docker and Go
Building Services With gRPC, Docker and Go
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.
 
Beyond php it's not (just) about the code
Beyond php   it's not (just) about the codeBeyond php   it's not (just) about the code
Beyond php it's not (just) about the code
 
Building Apps with MongoDB
Building Apps with MongoDBBuilding Apps with MongoDB
Building Apps with MongoDB
 
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Webbeyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
beyond tellerrand: Mobile Apps with JavaScript – There's More Than Web
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Solving performance issues in Django ORM
Solving performance issues in Django ORMSolving performance issues in Django ORM
Solving performance issues in Django ORM
 
PoEAA by Example
PoEAA by ExamplePoEAA by Example
PoEAA by Example
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
 
Giovanni Lanzani – SQL & NoSQL databases for data driven applications - NoSQL...
Giovanni Lanzani – SQL & NoSQL databases for data driven applications - NoSQL...Giovanni Lanzani – SQL & NoSQL databases for data driven applications - NoSQL...
Giovanni Lanzani – SQL & NoSQL databases for data driven applications - NoSQL...
 
How to Be a 10x Data Scientist
How to Be a 10x Data Scientist How to Be a 10x Data Scientist
How to Be a 10x Data Scientist
 

Mais de MongoDB

Mais de MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Fast REST APIs Development with MongoDB

  • 1. FAST REST APIS DEVELOPMENT WITH MONGODB Pablo Enfedaque Vidal @pablitoev56
  • 2. WHO? •  Pablo Enfedaque •  Computers Engineer •  Tech Lead and R&D software engineer at Telefonica Digital •  Working with MongoDB for some years.
  • 3. TELEFONICA DIGITAL. WHAT? •  Telefonica •  Fifth largest telecommunications company in the world •  Operations in Europe (7 countries), the United States and Latin America (15 countries) •  Movistar, O2, Vivo, Terra, Tuenti, Jahjah, Tokbox, everything.me, Open Web Device…
  • 4. TELEFONICA DIGITAL. WHAT? •  Telefonica Digital •  Web and mobile digital contents and services division •  Product Development and Innovation unit •  Products & services development, research, technology strategy, user experience, deployment & operations… •  Around 70 different on going projects
  • 5. OUR PROJECTS •  Full product development, with life cycle and several deployments •  20 people team, 1 year or more •  Pilot or small product to be deployed in a certain environment •  6 people team, 6 months •  Seedbed or proof of concept to be run with reduced set of users •  3 people team, 3 months •  Ten Fridays open exploratory project to work on your ideas •  2 people team, 10 days (consecutive Fridays)
  • 6. SO… FAST DEVELOPMENT IS REALLY CRUCIAL FOR US
  • 7. HOW TO SPEED UP OUR DEVELOPMENTS? •  Agile methodologies •  Lean startup •  eXtreme Programming •  Continuous Integration •  …
  • 8. HOW TO SPEED UP OUR DEVELOPMENTS? CHOOSE THE RIGHT TECHNOLOGY (AT FIRST)
  • 10. THE RIGHT TECHNOLOGY •  Faster development with Dynamic Languages •  3x •  4x •  10x
  • 11. THE RIGHT TECHNOLOGY THE SAME CAN BE STATED FOR •  3x MONGODB •  4x •  10x
  • 12. THE RIGHT TECHNOLOGY •  Several times faster development with Dynamic Languages •  Several times faster development with MongoDB AND BOTH TOGETHER IS A WIN WIN
  • 13. WHY? HOW? LET’S SEE SOME EXAMPLES
  • 15. JAVA VERSION public int[] getDims() { if (this.dims != null) { return this.dims; } BasicDBObject query = new BasicDBObject(); query.put("_id", "ctxt_dimensions"); DBObject setup = setup_coll.findOne(query); BasicDBList dbl = (BasicDBList)setup.get("dims"); this.dims = new int[dbl.size() + 2]; BasicDBObject users_counter_ref = new BasicDBObject("_id", users_coll_name); BasicDBObject apps_counter_ref = new BasicDBObject("_id", apps_coll_name); dims[0] = (Integer)counters_coll.findOne(users_counter_ref).get("value") + 1; dims[1] = (Integer)counters_coll.findOne(apps_counter_ref).get("value") + 1; for (int i=0; i<dbl.size(); i++) { dims[i + 2] = (Integer)dbl.get(i); } return dims; }
  • 16. PYTHON VERSION def get_dims(self): ud = self.counters_coll.find_one({'_id': 'users'})['value'] ad = self.counters_coll.find_one({'_id': 'applications'})['value'] res = [ud, ad] res.extend(self.setup_coll.find_one({}, {'dims': 1})['dims']) return res IT’S UP TO YOU…
  • 18. LET’S PLAY TO SPOT THE DIFFERENCES
  • 19. EXAMPLE: SPEAKER JSON { "name": "Pablo Enfedaque", "company": "Telefonica Digital", "accepted": true, "registration_date": "2012-03-15T14:35:05", "num_talks": 1, ”votes": 4, "email": "pev@td.com" }
  • 20. EXAMPLE: DECODED JSON (PYTHON) { "name": "Pablo Enfedaque", "company": "Telefonica Digital", "accepted": True, "registration_date": datetime(2012, 3, 15, 14, 35, 5), "num_talks": 1, ”votes": 4, "email": "pev@td.com" }
  • 21. EXAMPLE: MONGODB BSON { "name": "Pablo Enfedaque", "company": "Telefonica Digital", "accepted": true, "registration_date": ISODate("2012-03-15T14:35:05Z"), "num_talks": 1, ”votes": 4, "email": "pev@td.com", ”_id": ObjectId("5142d08c5db1362abc2d208b”) }
  • 23. SPEAKER CREATION decoded_input = json.loads(input_json) decoded_input['registration_date'] = datetime.strptime(decoded_input['registration_date'], "%Y-%m-%dT%H:%M: %S”) return dbconn['speakers'].insert(decoded_input) > ObjectId('5142d2845db1362bb3155322')
  • 24. SPEAKER RETRIEVAL retrieved = dbconn['speakers'].find_one({'name': 'Pablo'}, {'_id': 0}) retrieved['registration_date'] = retrieved['registration_date'].strftime("%Y-%m-%dT%H:%M:%S") return retrieved
  • 26. WHAT IF WE WANT TO CHANGE SPEAKERS DATA?
  • 27. EXAMPLE: SPEAKER JSON { "name": "Pablo Enfedaque", "company": "Telefonica Digital", "position": "R&D SW Engineer", "accepted": true, "registration_date": "2012-03-15T14:35:05", "num_talks": 1, ”votes": 4.3,  WAS AN INTEGER "email": "pev@td.com" }
  • 28. SPEAKER CREATION decoded_input = json.loads(input_json) decoded_input['registration_date'] = datetime.strptime(decoded_input['registration_date'], "%Y-%m-%dT%H:%M: %S”) return dbconn['speakers'].insert(decoded_input) SPEAKER RETRIEVAL retrieved = dbconn['speakers'].find_one({'name': 'Pablo'}, {'_id': 0}) retrieved['registration_date'] = retrieved['registration_date'].strftime("%Y-%m-%dT%H:%M:%S") 0 LINES CHANGED return retrieved
  • 30. SPEAKER VALIDATION from rest_framework import serializers class SpeakerSerializer(serializers.Serializer): name = serializers.CharField(max_length=150) company = serializers.CharField(max_length=150) position = serializers.CharField(required=False) accepted = serializers.BooleanField() registration_date = serializers.DateTimeField() num_talks = serializers.IntegerField() votes = serializers.FloatField() email = serializers.EmailField(max_length=150) def restore_object(self, attrs, instance=None): return attrs
  • 31. SPEAKER CREATION decoded_input = json.loads(input_json) serializer = SpeakerSerializer(decoded_input) print dbconn['speakers'].insert(serializer.object) SPEAKER RETRIEVAL retrieved = dbconn['speakers'].find_one({'name': 'Pablo'}) serializer = SpeakerSerializer(retrieved) return serializer.object
  • 32. DON’T LIKE TO WORK WITH DICTIONARIES / HASHES?
  • 33. CUSTOMISE ATTRIBUTES ACCESS class AttrDict(dict): def __getattr__(self, name): try: return super(AttrDict, self).__getitem__(name) except KeyError, e: raise AttributeError(e) def __setattr__(self, name, value): if name in self: super(AttrDict, self).__setitem__(name, value) else: super(AttrDict, self).__setattr__(name, value)
  • 34. USE DICTIONARIES AS OBJECTS decoded_input = json.loads(input_json) serializer = SpeakerSerializer(decoded_input) speaker_obj = AttrDict(serializer.object) print speaker_obj.company print speaker_obj['position'] > Telefonica Digital R&D SW Engineer
  • 36. NO
  • 37. OBJECT-RELATIONAL MAPPER NO RELATIONAL  NO ORM NEEDED
  • 39. CONCLUSIONS •  MongoDB + dynamic languages = fastest development speed •  14 months project with Oracle à 3 months project with MongoDB •  REST API best practices •  Use JSON •  Use dictionaries / hashes •  Access dictionaries as objects •  No relational model à no ORM •  No other mappers •  Use decorators to handle AutoReconnect