Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Effective Design of RESTful APIs

This presentation will help you plan and model your own APIs and understand the six REST design constraints that help guide your architecture.
by

Mohamed Taman

on 13 May 2017

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Effective Design of RESTful APIs

Effective Design of
RESTful
APIs

REST Modeling & design constraints that help guide your Architecture.
GOAL!
Thank you!
Three approaches to adding an
API
Tips for modeling APIs
Creating & Grouping API methods
Mapping our Activities to
Nouns
&
Verbs
HTTP Headers & Response codes
This information is hidden from user, but not for tools.
REST APIs:
The six Constraints
HTTP Overview
HTTP is a great tool
Agenda
Let's Go
Tips for API Modeling
Don't worry about the tools.

Have a consistent process.

It doesn't count unless it's written down.
The Patron (You).

The Cashier.

Baristas.

Other Customers.
Validate your API
Write each Resource's actions on notecards.

Use notecards to map out each flow, action, etc.
HTTP Responses
&
Payloads
REST Constraints
Client - server.
Stateless.
Cacheable.
Layered System.
Code on Demand (Optional).
Uniform Interface.
Who are our participants
213.245.209.34,
Show me your home page
dev.opera.com
HTTP OK - 200
Here you go:
<html>......
API Design is hard
What functionality to expose.
How to expose it.
How best way to expose it.
How to adjust & improve.
There are only two hard things in computer science :
Cache invalidation
&
naming things
Phil Karlton, Quoted by
Martin Fowler
an
affordance
is something which allows you to perform an action or accomplish a goal.
Mike Amundsen
http://amundsen.com/blog/archives/1109
Affordances
What the API allows you to do.

What the API makes easy.

What the user, wants to accomplish.
Affordances in practices
let's talk about coffee cups...
Coffee Cups
Handles are Great
Designed for holding when contents are hot.

Easy for holding.

Can be used for other things.
Adding an API
1- Bolt-On Strategy
Brute force approach, but generally is the fastest way to get something useful.
Takes advantages of existing
code
and
systems
.
Problems
in the application tend to "
Leak through
" into the API.
2-
Greenfield
Strategy
Generally the "
API first
" or
"
Mobile first
" mindset.
Takes advantages of new technologies, possibility reinvigorate the
Team
.
Not always possible to drive business value
quickly
or
easily
.
3- Facade Strategy
Wraps existing
logic
,
replace
as you go.
Ideal for
legacy systems
as application is always
functional
.
Can be
challenging
with "multiple mindset" in the system.
Modeling
is your key to success
I want to layout three simple rules:
Don't worry about the
tools
.
Have a
Constance
process.
It doesn't count unless it's
written down
Document everything and you can de-prioritize everything later.
Identifying Participants
For each participant we need to capture
Who they are.

Is they external or internal to organization.

Short description who they are.
Let's see coffee shop example!
Who are our participants?
The Patron (you).

The cashier.

Baristas.

Other customers.
Identifying activities and breaking them into steps
What are our activities? (rev 1)
You place and order.

You wait for the order.

You receive the order.
This isn't complete, it just describe you,
so let's try again
What are our activities? (rev 2)
The patron, you, creates an order with the cashier.
Challenge:
Identifies participants and activities to order book online?
I assume that the books are in the stock with no return.
Who are our participants?
System Admin.

Developers.

The Customer.

Customer Support.
What are our activities?
Place order.
Look up order status.
Cancel order.
Add items to cart.
Remove items from the cart.
Clear cart.
Checkout process.
Step 1:
Identify Participants
Step 2:
Identify Activities
Step 3:
Break into steps
Step 4:
Create API Definition
Step 5:
Validate Your API
Review last Challenge:
Identifies participants and activities
to order book online?
4- Create API definition
1- Identify
the resources
Item Resource
List items.

View items.

Search Items.

Add/Edit items.
Cart Resource
Add item.

Remove item.

Clear Cart.

View Cart.

Checkout.
Orders Resource
List orders for customer.

Obtain Order Status.

Cancel Order.
Customer Resource
View Customer.

Search Customer.

Add/Edit Customer.
2- Map Activities to
Resource lifecycle.
Map Actions to HTTP
Nouns & Verbs.
Take discovered actions to
GET, POST, PUT, & DELETE
Items Resource
Activity
Verb/Noun Mapping
List items
Edit items
Add items
Search for items
View item
GET
/items
PUT
/items/:id
POST
/items/
GET
/items?search=param
GET
/items/:id
Carts Resource
Activity
Verb/Noun Mapping
Add item
Checkout
View Cart
Clear Cart
Remove item
?????
GET
/carts/:id
DELETE
/carts/:id
?????
?????
Customers Resource
Activity
Verb/Noun Mapping
Search for customers
Edit customer
Add customer
View customer
PUT
/customers/:id
POST
/customers/
GET
/customers?search=param
GET
/customers/:id
Orders Resource
Activity
Verb/Noun Mapping
List order for customer
Cancel order
Obtain order status
GET
/orders/:id
DELETE
/orders/:id
GET
/orders/:id
3- Mapping remaining
Activities
to
custom
actions
.
Designing Relationships
Three types.
Relationships Types
Independent
- The resources may exists regardless of the other existing, but they may reference each other.
Dependent
- One resource can not exists without the parent.

Associative
- they are independent but the relationship contains additional properties to describe it.
Questions to define the Relationships:
Can the resource exist without one another?
Does one resource only exist when the other exists?

Does the relationship between resources require more information than just the links between them?
Carts Resource
Activity
Verb/Noun Mapping
Add item
Checkout
View Cart
Clear Cart
Remove item
GET
/carts/:id
DELETE
/carts/:id
POST
/carts/:id/items/:item_id
DETETE
/carts/:id/items/:item_id
POST
/carts/:id/checkout
For example, which are which
/movies/:id
/movies/:id/actors
/movies/:id/characters
/movies/:id/characters/:id
/actors/:id
actors/:id/movies/:id
actors/:id/characters/
actors/:id/characters/:id
Validating your API
Validate your API
Write each resource's actions on a notecards.
Use notecards to map out each flow, action, etc.
Fill in any gaps you might be missing, assign them to resources as appropriate.
Challenge
: Validating your API model.
Challenge objectives
Handle a missing order
Reorder the same order as last time.
Cancel part of an order.
Solution
My Order is missing!
Customer service lists the customer's orders.
Customer Service obtains the customer's order status.
Reorder the same thing as last time.
Customer views a previous order.
Customer copies order (new?)
Customer checks out.
Part of my order is wrong.
Customer service lists the orders.
Customer Service views the active order.
Customer Service cancels specific items. (new?)
213.245.209.34,
Show me your home page
dev.opera.com
HTTP Responses &
Payloads
HTTP OK - 200
Here you go:
<html>......
Understood by most clients, and tools out there.

Underlies the entire web.
REST
is
NOT
a standard
REST
is
NOT
a pretty
urls
, not necessarily
XML
or even
JSON
REST is a generally agreed upon set of
principles
or
constraints
.
SOAP
vs
REST
a
mortgage
vs
borrowing
$10
HTTP
Well understood protocol.

Simple and powerful in its implementation.
In order to access payload:
Live header
add-on available on
Chrome
and
Firefox
.

Postman
add-on for chrome, great client tool.

Command line tool
CURL

curl
-I
http://mobiledeveloperweek.com
Mohameds-MacBook-Pro:~ mohamed_taman$ curl -I http://rigadevday.lv

HTTP/1.1 200 OK
Date: Tue, 20 Jan 2015 13:58:31 GMT
Content-Type: text/html; charset=utf-8
Status: 200 OK
Connection: keep-alive
Set-Cookie: __cfduid=d17a5f26655bf860e6d5e193b4beaf1f91421762311; expires=Wed, 20-Jan-16 13:58:31 GMT; path=/; domain=.rigadevday.lv; HttpOnly
Last-Modified: Mon, 19 Jan 2015 22:12:48 GMT
Expires: Tue, 20 Jan 2015 14:08:31 GMT
Cache-Control: max-age=600
Server: cloudflare-nginx
CF-RAY: 1abbc99071080c95-AMS
Most important headers for your API are:
Status
- This is the response code of what you are trying to accomplish either successful or failed.
Content-Type
- It identifies the type of payload being passed back by the server.
Media-Type
- It describes the actual structure of the payload and how things work together.
HTTP response code classes:
1xx
Informational.
2xx
Success.
3xx
Redirect.
4xx
Client error.
5xx
Server error.
HTTP response code - 2xx
200
OK.
201
Created.
202
Accepted.
204
No Content.
HTTP response code - 3xx
301
Moved Permanently.
302
Moved Temporarily.
HTTP response code - 4xx
400
Bad Request.
401
Authentication Required.
402
Forbidden.
404
Not Found.
Response Codes are Great
Please
DON'T
create your own
REST Constraints
Client - server.
Stateless.
Cacheable.
Layered System.
Code on Demand (Optional).
Uniform Interface.
Client - Server
Web browser and a web server.
By separating the two, we can vary them.
Serve the Scalability and Reliability.
Stateless
Each requests stands on its own.
Requested can be processed in any order.
Because sometimes they will be!
-d 'From=01005318017'
curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/ACxxxx/SMS/Messages.xml
-d 'To=01005138433'
-d 'Body=Never+gonna+give+you+up.+Never+gonna+let+you+down.'
-u ACxxxx:{AuthToken}
Stateless - Why?
Flexibility
Stability
Reliability
Caching and Cacheability
Cacheable API
Each message should describe whether it's casheable.
Improves network and application usage.
Makes the system more reliable and scalable.
Cacheable
GET, PUT, and DELETE should be idempotent or "safe" .
The word "safe" means that if a given HTTP method is invoked, the resource state on the server will remain unchanged.
POST can be used for multiple operations so can't be cached.
Etags are awesome
Built for cache signaling.
Generated for individual requests, sent in the header.
Compares to see if anything has changed.
For more information: http://en.wikipedia.org/wiki/HTTP_ETag
Available via the HEAD verb.
REST Constraints
Layered systems
Layered systems.
Code on Demand
Uniform Interface
(optional)
Stateless API
Don't count on the client interacting directly with the server.
We use this on the web every single day.
Adds silent, invisible dependencies.
Layered Systems
Allow in between systems to add/remove functionality.
Allow load balancers, caches, logging, authorization, etc.
Layered Systems - Why?
Code On Demand
A request doesn't just retrieve the resource but also code that acts upon it.
We don't have to know or understand the code, just how to run it.
Allows for flexibility, and upgradability.
Optional
Code On Demand
Optional
Executing third party code is a security
nightmare
Umm.... gmail?
Uniform Interfaces
Identification of the request.
Manipulations of resources through these representations.
Self-descriptive message.
Uniform interface - Principals
Hypermedia as the engine of the application state (
HATEOAS
).
Should be
present
in every API.
it is most
complex
but
most
powerful
at all.
Generally:
/noun/id
/noun/action/id

but not required
/n=noun&id=id
/n=noun&a=action&id=id
Identification of the request.
Client interacts with a network application entirely through hypermedia provided
dynamically
by application servers. A REST client needs
no prior knowledge
about how to interact with any particular application or server beyond a generic understanding of
hypermedia
.

Source:

http://en.wikipedia.org/wiki/HATEOAS
HATEOAS
Manipulations through those interfaces
Each message should tell you:

If that resource is casheable.

How to process itself.

How to request the next resource.
Self-descriptive message
Within Twilio:
/2010-04-01/Accounts/{AccountSid}/Calls/{CAxxx}
/2010-04-01/Accounts/{AccountSid}/Recordings/{RExxx}
/2010-04-01/Accounts/{AccountSid}/SMS/{SMxxx}

GET
{all}
POST
{only for Calls and SMS}
PUT
n/a
DELETE
{only for Recordings}
Request:
GET /account/12345 HTTP/1.1
Host: somebank.org
Accept: application/xml
...
HATEOAS - example
Response:
HTTP/1.1 200 OK
Content-Type: application/xml
Content-Length: ...

<?xml version="1.0"?>
<account>
<account_number>12345</account_number>
<balance currency="usd">100.00</balance>

<link rel="
deposit
" href="
/account/12345/deposit
" />
<link rel="
withdraw
" href="
/account/12345/withdraw
" />
<link rel="
transfer
" href="
/account/12345/transfer
" />
<link rel="
close
" href="
/account/12345/close
" />
</account>
Mohameds-MacBook-Pro:~
curl https://api.github.com
{
"current_user_url": "https://api.github.com/user",
"current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}",
"authorizations_url": "https://api.github.com/authorizations",
"code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
"emails_url": "https://api.github.com/user/emails",
"emojis_url": "https://api.github.com/emojis",
"events_url": "https://api.github.com/events",
"feeds_url": "https://api.github.com/feeds",
"following_url": "https://api.github.com/user/following{/target}",
"gists_url": "https://api.github.com/gists{/gist_id}",
"hub_url": "https://api.github.com/hub",
"issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",
"issues_url": "https://api.github.com/issues",
"keys_url": "https://api.github.com/user/keys",
"notifications_url": "https://api.github.com/notifications",
"organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",
"organization_url": "https://api.github.com/orgs/{org}",
"public_gists_url": "https://api.github.com/gists/public",
"rate_limit_url": "https://api.github.com/rate_limit",
"repository_url": "https://api.github.com/repos/{owner}/{repo}",
"repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",
"current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",
"starred_url": "https://api.github.com/user/starred{/owner}{/repo}",
"starred_gists_url": "https://api.github.com/gists/starred",
"team_url": "https://api.github.com/teams",
"user_url": "https://api.github.com/users/{user}",
"user_organizations_url": "https://api.github.com/user/orgs",
"user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",
"user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"
}
HATEOAS - example 2

Mohamed Taman
@_tamanm

Innovation & R&D Sr. Manager @e-finance, Enterprise Architect, Java Champions, JCP,
Speaks Java, Author, IoT Geek

http://tamanmohamed.blogspot.com
http://www.linkedin.com/in/mohamedtaman
https://github.com/mohamed-taman
mohamed.taman@gmail.com
http://about.me/mohamedtaman/
The cashier passes the order to the barista.
The barista acknowledges the order and adds it to the queue.
As orders are processed, inventory and machines are tracked.
The customers receive their orders.
As orders are ready, they are announced and delivered.
Full transcript