Develop a Basic REST API from Scratch Using TDD with Val Karpov
1. Developing a Basic REST API from
Scratch Using TDD
Valeri Karpov
NodeJS Engineer, MongoDB
www.thecodebarbarian.com
github.com/vkarpov15
@code_barbarian
2. *
What is this talk about?
•Earlier you heard about:
– Building a basic app
– Schema design principles
•MongoDB is great for storing web/mobile app data
•So let’s build a REST API using NodeJS!
•+ learn a bit about test-driven dev with NodeJS
3. *
Overview
•Part 1: Shopping Cart Application
– Search for products
– Add them to your cart
– Check out with Stripe
•Part 2: Using the Mongoose ODM
•Part 3: Schema Design
•Part 4: Building an API with the Express framework
•Part 5: Testing with Mocha + Superagent
7. *
App Structure
•"Bad programmers worry about the code. Good
programmers worry about data structures and their
relationships." - Linus Torvalds
•3 schemas for 3 collections:
•Products
•Categories
•Users
18. *
Category Schema Queries
•What categories are descendants of “Electronics”?
•
•What categories are children of “Non-Fiction”?
•
•What categories are ancestors of “Phones”?
20. *
Category Schema Takeaways
•Queries in MongoDB should be simple
•“Store what you query for”
•“If you need [to use the aggregation framework in
an API endpoint], you're screwed anyway, and
should fix your program.” - Linus Torvalds
22. *
Principle of Least Cardinality
•Product and user = many-to-many relationship
•Don’t necessarily need a mapping table
•User won’t have 1000s of products in cart
•Can represent relationship as array in user since
one side is small
•Arrays that grow without bound are an
antipattern!
23. *
Part 4: The Express Framework
•Most popular NodeJS web framework
•Simple, pluggable, and fast
•Great tool for building REST APIs
37. *
Part 4 Takeaways
•Express REST API on top of mongoose
– Access control
– Business logic
– Define what operations user can take on database
•Mongoose casting and validation for APIs
38. *
Part 5: Test-Driven Development
•Building an API is tricky
•Lots of different error conditions
•Express has a lot of magic under the hood
39. *
NodeJS Concurrency and Testing
•NodeJS runs in an event loop
•Single threaded
•Can run client and server on same thread!
•Test server end-to-end
44. *
Part 5 Takeaways
•NodeJS concurrency makes testing easy
•Not just unit tests - full E2E for your REST API
•Can manipulate database and make arbitrary
HTTP requests
45. *
•Upcoming EdX Video Course
•Looking for beta testers! Fill out survey for info
– database.mongodb.com/community-survey
•More NodeJS+MongoDB content at:
– www.thecodebarbarian.com
– Twitter: @code_barbarian
Thanks for Listening!