Restful APIs 101 Laura Heritage @heritagelaura Laura.heritage@akana.com
Agenda REST Fundamentals Akana API Designer Cloud9 and Ionic
The Glory of REST Richardson’s Maturity Model Roy Fielding definition of RESTFul HATEOAS GET, PUT, POST, DELETE /books/1 and /books/2 POST Ah the Glory of REST what we all should aspire to. Or should we? This Maturity Model is pretty popular in the industry now especially around the hypermedia arena. If this is your first time seeing it let me explain the levels and you can see where you fall Level 0: You could consider this plain old XML. You have a single endpoint in which you send a request and you get back an XML response and then then you send the next request. (Normally POST) Typically SOAP request here Level 1: Resources are introduced. Still this level usually only uses one method like POST Level 2: Next level is the Verbs (GET, PUT, POST, DELETE) and using the appropriate response codes. For example when something goes wrong, don’t just use 200 (OK) Level 3: Level uses HATEOAS to deal with discovering possibilities of your API (Hypermedia as the Engine of Application State) Richardson’s Maturity Model http://martinfowler.com/articles/richardsonMaturityModel.html
Pragmatic
REST is Made Up of Resources and Actions Resource - An Entity that you want to expose that can be named For example: accounts, users, invoices, transactions Actions – What you can preform on the Resources using the HTTP method GET, PUT, POST, DELETE, PATCH GET /accounts – Retrieves a list of Accounts POST /accounts – Creates a new Account
Basic REST Guidelines (Principles) 2 URI’s per resource 1. Listing (collection) - /v1/accounts 2. Detail - /v2/accounts/{id} Use nouns instead of verbs to name resources WRONG: /v1/getAllAccounts CORRECT: /v1/accounts Prefer plurals over singular: /accounts over /account lower case over camel case lower case /accounts camel case /Accounts For associations: /resource/{id}/resourceIn example: /accounts/1234/invoices
Accounts URL Endpoints Use Case What you are tempted to do: Proper REST URL To get all Accounts /v1/get-all-accounts /v1/accounts To get a particular Account /v1/get-account/{id} /v1/accounts/{id} To create an Account /v1/create-account/{id} To delete an Account /v1/delete-account/{id} To update an Account /v1/update-account
Tell The Server What Action to Perform HTTP Request Method Maps To: CRUD Operation GET -> Read (Show) POST Create PUT Update (the whole resource) DELETE Destroy PATCH Update (updating a partial resource) OPTIONS Allowed Verbs (Not used too often) HEAD Headers Only
Accounts URL Endpoints Use Case HTTP Method: Proper REST URL To get all Accounts GET /v1/accounts To get a particular Account /v1/accounts/{id} To create an Account POST To delete an Account DELETE To update an Account PUT
What About Relationship? Linked Resources /v1/accounts/{id}/invoices /v1/accounts/{id}/billing_info To embed or not? If a resource can live independently then do not embed. If it can not live independently then embed.
Keep complexity behind the “?” Variations Keep complexity behind the “?” /accounts?type=corporate&country=us /accounts?type=consumer&country=uk /billing_info?type=credit_card /billing_info?type=checking
Pagination /accounts?limit=25&offset=50 Send total entries back to user – For example, in custom HTTP header: X-Total-Count Provide links to next or pervious page - For example in HTTP header: Link
Version /v1/accounts /v2/accounts While there are several ways to represent versions. This is the preferred method /v1/accounts /v2/accounts
Give Me Exactly What I Need And no more.. /accounts?fields=first_name,last_name,address
HTTP Codes and Messages HTTP Codes are for Code HTTP Status Code: 401 Message is for people { “Status” : “401”, “messsage”: “Authenticate”, “code” : 20003, “moreinfo” : http://www.twilio.com/docs/errors/20003 } This is the best. When you provide a link to more information
Types of Status Codes Success - Everything worked Client error - The application did something wrong Server error - The API did something wrong 200 - OK 400 - Bad Request 500 - Internal Server Error
Top 10 HTTP Codes 200 OK 201 CREATED 204 NO CONTENT 400 BAD REQUEST 401 UNAUTHORIZED 403 FORBIDDEN 404 NOT FOUND 405 METHOD NOT ALLOWED 409 CONFLICT 500 INTERNAL SERVER ERROR
What If It Doesn’t Fit To CRUD First Make Sure it Really Doesn’t Restructure the action to appear like a field of a resource. This works if action doesn’t take parameters For example the activate action could be mapped to a boolean activated field and updated via PATCH to the resource Treat like a sub-resource with RESTful principles. For example, GitHub’s API lets you star a gist with PUT /gists/:id/star - Star a gist DELETE /gists/:id/star - Unstar a gist Sometimes you have really no way to map the action to a sensible RESTFul structure. For example, a multi-resource search doesn’t really make sense to be applied to a specific resources endpoint. In this case, /search would make the most sense even though it isn’t a resource.
Don’t Expose The Complexities Of Your Existing Information System Design for the developer audience who is going to use it. Application API Layer Client Application Interface /entrypoint /collection1 /resource 1 /resource 2 /collection /resource1 /resource2 …. HTTP Client App REST Library Optional HTTP Library Application Data Model Resource Model server client
How Akana Fits Into Your Existing Architecture Security Services
Additional Recommended Practices Treat each API as a product Know your audience and their use cases Design for consumption Document wisely – they shouldn’t need to know the internal architecture to use your API Ensure great intuitive error handling Offer both JSON & XML Use HTTP headers for serialization format Content-Type Accept GET methods and Query parameters should not alter state Look at great APIs in the market and steal concepts from them.
Tools Available For Hackathon Developer Portal API Designer API Creation IDE for Node.js Great for team development Integrates with GitHub Open source mobile SDK for HTML5 Based on Node.js and Cordova Allows you to rapidly build mobile applications Server Side Javascript We will be leverage Express – A framework on top of Node.js to build RESTful APIs Open-source document database - highly performant, high availability, automatic scaling. https://docs.mongodb.org/manual/introduction/
Demo Of Akana Portal
Today We are Using Node.JS On Cloud 9
Demo of Cloud 9
Install Ionic in Cloud9 Create a Node.js workspace From the workspace’s terminal run: npm i cordova ionic -g ionic start myApp cd myApp ionic serve -a $IP -p 8080 -r 8081
To Add a New Tab To myApp Example Create New Factory (usbankservices.js Modify controllers.js Create new tab (tab-usbank.html) Modify tads.html Modify index.html Modify app.js
usbankservices.js
index.html
Controller.js Add a controller
tab-usbank.html
tabs.html
App.js
Download code npm i myappUSBankExample cd to node_module/myappUSBankExample npm install ionic serve -a $IP -p 8080 -r 8081
API Resources and API University Resource Center http://resource.akana.com/ Follow us on: https://www.linkedin.com/company/akana https://twitter.com/AkanaInc
Back Up Reference Slides