Why and how MongoDB is a perfect match for building your next RESTful Web API. Presented at: NoSQL Day 2013 (Udine, Italy), MongoTorino 2013 (Turin, Italy), A Morning With MongoDB (Milan).
12. Constraints
• minimum viable product first
• add features over time
• frequent database schema updates
• avoid downtime as much as possible
17. JSON & RESTful API
GET
Client
Mongo
JSON!
JSON!
accepted media type
(BSON)
maybe we can push directly to client?
18. JSON & RESTful API
GET
Client
API
JSON!
JSON!
accepted media type
subset of python dict!
(kinda)
almost.
Mongo
JSON!
(BSON)
19. JSON & RESTful API
POST
Client
JSON!
objects
API
JSON/dict!
maps to python dict!
(validation layer)
Mongo
JSON!
(BSON)
also works when posting (adding) items to the database
22. What about Queries?
Queries in MongoDB are represented as JSON-style objects
// select * from things where x=3 and y="foo"
db.things.find({x: 3, y: "foo”});
28. Also in MongoDB
• setup is a breeze
• lightweight
• fast inserts, updates and queries
• excellent documentation
• great support by 10gen
• great community
33. Resource GET
/contacts?where={“age”: {“$gt”: 20}}&projection={“lastname”: 1}
def get_collection(collection):!
documents = []!
cursor = db(collection).find(where, projection)!
for document in cursor:!
documents.append(document)!
return documents
find() accepts a python dict
as query expression, and
returns a cursor we can
iterate
34. Resource GET
/contacts?where={“age”: {“$gt”: 20}}&projection={“lastname”: 1}
def get_collection(collection):!
documents = []!
cursor = db(collection).find(where, projection)!
for document in cursor:!
documents.append(document)!
return documents
find() accepts a python dict
as query expression, and
returns a cursor we can
iterate
35. Resource GET
/contacts?where={“age”: {“$gt”: 20}}&projection={“lastname”: 1}
def get_collection(collection):!
documents = []!
cursor = db(collection).find(where, projection)!
for document in cursor:!
documents.append(document)!
return documents
find() accepts a python dict
as query expression, and
returns a cursor we can
iterate
42. PATCHing
def patch_document(collection, original):!
(...)!
# Perform the update!
db(collection).update({"_Id": ObjectId(object_id)}, !
{"$set": updates})!
$set accepts a dict!
with the updates for the db
eg: {“active”: False}.
updates are atomic
44. POSTing
Take #1
def post(collection):!
(...)!
for key, item in docs.items():!
response[ID_FIELD] = db(collection).insert(item)
push document and get its
ObjectId back from Mongo.
like other CRUD operations,
inserting is trivial in
mongo.