Writing RESTful Web Services

Post on 13-Apr-2017

171 views 0 download

Transcript of Writing RESTful Web Services

Writing RESTful Web ServicesCodeweavers Development Series

Introduction● What is a RESTful Web Service?● How should we create one?● Some Tips, Tricks and Guidelines● Introduction to HATEOAS, HAL & JSON-LD● REST vs RPC

2

RESTRepresentationalStateTransfer

3

Roy Thomas Fielding’s PhD Thesis- Architectural Styles and Design of

Network-based Software Architectures (2000)

HTTPDeveloped alongside HTTP 1.1

REST doesn’t define a standard protocol but HTTP is most commonly used

4

RESTfulREST isn’t a standard but a style for creating systems

Systems that follow observe REST constraints are said to be RESTful

5

ArchitecturePerformance

ScalabilitySimplicity

ModifiabilityVisibility

PortabilityReliability

6

Architectural ConstraintsClient-Server

(Representations & Messages)

StatelessCacheable

LayeredUniform Interface

7

RepresentationsResources

How to provide access to resources{ "ID": "1", "FirstName": "Paul", "LastName": "Boocock", "Email": "paulboocock@codeweavers.net"}

Could also be XML

8

RepresentationsResources can contain other resourcesClient and Server can comprehendCan completely represent the resource

Break big resources down into smaller onesRepresentations can link to each other

9

CacheableStore the results and on the next request serve the same responseCaching can be controlled with HTTP Headers

Date, Last Modified, Cache-Control, Expires, Age

Be careful you don’t start serving stale results10

StatelessDo not maintain state for any client

HTTP is stateless by designBad Design:

https://OrderService/Orders/1https://OrderService/Orders/NextOrder

11

LinksSay hello to HATEOAS!

Hypermedia as the engine of application stateThese can be generated dynamicallyAllow clients to transition through the supported actions by the server

12

Uniform InterfaceRESTful systems should have a Uniform Interface

HTTP v1.1 provides thisURIs to identify resourcesHTTP Verbs to manipulateHTTP Headers to help parse (MIME Types)Hyperlinks to navigate

13

RESTful Web ServicesClients and Servers have to talk to each other

Commonly use HTTP

Client sends a requestServer replies with a response

14

HTTP RequestsVerbs

UriHTTP Version

HeadersBody

15

HTTP ResponseHTTP Version

Response CodeHeaders

Body

16

Addressing ResourcesEach resources should have at least one URIA typical convention:

Protocol://ServiceName/ResourceType/ResourceID

The HTTP Verb decides the operation performed

17

Addressing ResourcesUse plural nouns for naming resourcesAvoid spacesBe consistent!Take your time, a good URI will stick aroundAvoid verbs for resource names

BAD: https://OrderService/RetrieveOrder/118

Idempotent or Not?A service that can be called multiple times without different outcomes is Idempotent.

Safe methods are ones which do not modify a resource.

19

VERBS

20

Method Operation performed on server Safe Idempotent

GET Read a resource. Yes Yes

PUT Insert a new resource or update if the resource exists. No Yes

POST Insert a new resource. Also can be used to update an existing resource.

No No

PATCH Update a resource with a partial update or instruction No No

DELETE Delete a resource. No Yes

OPTIONS List the allowed operations on a resource. Yes Yes

HEAD Return only the response headers and no response body. Yes Yes

PUT vs POST vs PATCH

21

PUT Insert a new resource or update if the resource exists. No Yes

POST Insert a new resource. Also can be used to update an existing resource.

No No

PATCH Update a resource with a partial update or instruction No No

Status CodesHTTP Responses contain status codes

These can be used to indicate success or failures of the request

2xx for Success4xx for Bad Request (You messed up)5xx for Server Error (We messed up)

22

Status CodesDon’t get carried away with Status Codes

Keeping usage of them simple is probably a good idea

Imagine having to handle every status code…Some nice ones though, like a 201 for Post

23

Handling ErrorsDon’t just use Status Codes for errors

400 Bad Request, 404 Not Found500 Internal Server Error

You should have a Errors array on the top level of your response

Code, Title, Message, Links, Source24

VersioningAPIs should be versioned

New version should be created on a breaking change

25

Breaking ChangesWhat is a breaking change?Depends!

Usually when something needs removing from the response or a new required field is added to the request Could be really strict! Any change...

26

LinksYou should be able to navigate a RESTful service just like a webpage

Should contain links to other relations

Some standards are starting to emerge...

27

HALHypertext Application Language

http://stateless.co/hal_specification.html

A number of NUGET Packages:https://www.nuget.org/packages/WebApi.Hal/https://www.nuget.org/packages/HoneyBear.HalClient/

28

JSON-LDA Linked Data format for JSON

http://json-ld.org/

Popular NUGET Package:https://www.nuget.org/packages/json-ld.net/

29

RPCRemote Procedure Call

Also uses HTTP ProtocolGET or POST an operation not a resourceOperations manipulate dataNo rules! Good to be consistent though.

30

REST vs RPCURIs represent:

REST = NounsRPC = Verbs

Similar in many waysREST is more predictable

31

REST vs RPC ExamplesRPC Options:

GET (or POST) /deleteItem?itemId=456GET (or POST) /removeIt?itemId=456GET (or POST) /trash?itemId=456

REST Option:DELETE /items/456

32

Other Stuff...CachingAuthorization Headers

ASP.Net Web Api 2...

33

ConclusionsThings don’t have to be RESTful to be right

Design consistent and reliable APIs

Don’t start Bikeshedding... 34

ConclusionsMake an educated decision on the right style for the task at hand

RESTful Services probably best for CRUD resourcesREST is good for public services as it is predictableDealing with Processes or Operations then a RPC style service might be betterRPC Services are arguably easier to designMaybe fewer calls with RPC Services?

35

Useful LinksJSON API - http://jsonapi.org/JSON-LD - http://json-ld.org/MS API Guidelines - https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.mdHTTP v1.1 - http://www.ietf.org/rfc/rfc2616.txt

36