Upgrade to Pro — share decks privately, control downloads, hide ads and more …

API.js

 API.js

Bootstrapping an API in node.js with express.js and Redis. Testing with Mocha and Documentation in iodocs and Dox.

PatrickHeneise

October 17, 2013
Tweet

More Decks by PatrickHeneise

Other Decks in Technology

Transcript

  1. What makes a good API? ★ Performance ★ Scalability ★

    Reusability ★ Evolvability ★ Documentation ★ Testability ★ Value ★ Easy to learn & use ★ Hard to misuse
  2. ‘Once you have a bad API, you can not change

    it. Forever. You’ve got one chance how to make it right.’ – Joshua Bloch, Google Tech Talk, Jan 2007
  3. But node.js has some nice features. And it’s cool. Because

    it’s JavaScript. And JavaScript is cool, right?
  4. ‘An API should do one thing, and to it well.’

    Joshua Bloch, Google Tech Talk, Jan 2007
  5. exports.show = function(req, res) { var id = req.params.id; redis.hgetall('junk:'

    + id, function (error, junk) { if (junk === null) { res.send(404); } else { res.send(200, junk); } }); };
  6. ★ params: /api/junk/1 ★ query: /api/junk?id=1 ★ body: /api/junk -d

    {‘id’: 1} ★ Choose your weapon carefully! Input
  7. ★ 200 - Success ★ 201 - Created ★ 204

    - No content ★ 401 - Unauthorized ★ 403 - Forbidden ★ 404 - Not Found ★ 409 - Conflict ★ 500 - Internal Server Error HTTP Status Codes
  8. describe('GET /junk/:id', function () { it('should return details of the

    junk', function (done) { request(url) .get('/junk/0') .set('apikey', 'asdasjsdgfjkjhg') .send() .end(function (error, response) { response.status.should.equal(200); response.body.text.should.equal('iz likin myself on lolcats.com'); should.exist(response.body.url); done(error); }); });
  9. before(function (done) { ! require('./before').before(function () { ! ! done();

    ! }) }); after(function (done) { ! require('./after').after(ids, function() { ! ! done(); ! }); });
  10. Junk GET /junks ✓ should return a list of junk

    GET /junk/:id ✓ should return details of the junk ✓ should fail with 404 POST /junk ✓ should create new junk ✓ should fail to create new junk DELETE /junk/:id ✓ should delete junk, huzzah! ✓ should fail to delete junk 7 passing (1s)
  11. ★ http://jsdox.org ★ https://github.com/visionmedia/ dox - JavaScript documentation generator ★

    https://github.com/mashery/ iodocs - I/O Docs - Open Source in Node.js
  12. Dox

  13. /** * Output a single piece of junk specified by

    :id * * @param {Number} id * @return {Object} All junk details * @api public */
  14. ★ How To Design A Good API and Why it

    Matters http://www.youtube.com/watch?v=aAb7hSCtvGw http://lcsd05.cs.tamu.edu/ slides/keynote.pdf ★ http://stackoverflow.com/ questions/2619854/best-practices- and-guidelines-for-designing-an- api ★ https://dev.twitter.com//