Writing RESTful Web Services

36
Writing RESTful Web Services Codeweavers Development Series

Transcript of Writing RESTful Web Services

Page 1: Writing RESTful Web Services

Writing RESTful Web ServicesCodeweavers Development Series

Page 2: Writing RESTful Web Services

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

Page 3: Writing RESTful Web Services

RESTRepresentationalStateTransfer

3

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

Network-based Software Architectures (2000)

Page 4: Writing RESTful Web Services

HTTPDeveloped alongside HTTP 1.1

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

4

Page 5: Writing RESTful Web Services

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

Systems that follow observe REST constraints are said to be RESTful

5

Page 6: Writing RESTful Web Services

ArchitecturePerformance

ScalabilitySimplicity

ModifiabilityVisibility

PortabilityReliability

6

Page 7: Writing RESTful Web Services

Architectural ConstraintsClient-Server

(Representations & Messages)

StatelessCacheable

LayeredUniform Interface

7

Page 8: Writing RESTful Web Services

RepresentationsResources

How to provide access to resources{ "ID": "1", "FirstName": "Paul", "LastName": "Boocock", "Email": "[email protected]"}

Could also be XML

8

Page 9: Writing RESTful Web Services

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

Page 10: Writing RESTful Web Services

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

Page 11: Writing RESTful Web Services

StatelessDo not maintain state for any client

HTTP is stateless by designBad Design:

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

11

Page 12: Writing RESTful Web Services

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

Page 13: Writing RESTful Web Services

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

Page 14: Writing RESTful Web Services

RESTful Web ServicesClients and Servers have to talk to each other

Commonly use HTTP

Client sends a requestServer replies with a response

14

Page 15: Writing RESTful Web Services

HTTP RequestsVerbs

UriHTTP Version

HeadersBody

15

Page 16: Writing RESTful Web Services

HTTP ResponseHTTP Version

Response CodeHeaders

Body

16

Page 17: Writing RESTful Web Services

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

Protocol://ServiceName/ResourceType/ResourceID

The HTTP Verb decides the operation performed

17

Page 18: Writing RESTful Web Services

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

Page 19: Writing RESTful Web Services

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

Page 20: Writing RESTful Web Services

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

Page 21: Writing RESTful Web Services

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

Page 22: Writing RESTful Web Services

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

Page 23: Writing RESTful Web Services

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

Page 24: Writing RESTful Web Services

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

Page 25: Writing RESTful Web Services

VersioningAPIs should be versioned

New version should be created on a breaking change

25

Page 26: Writing RESTful Web Services

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

Page 27: Writing RESTful Web Services

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

Page 28: Writing RESTful Web Services

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

Page 29: Writing RESTful Web Services

JSON-LDA Linked Data format for JSON

http://json-ld.org/

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

29

Page 30: Writing RESTful Web Services

RPCRemote Procedure Call

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

30

Page 31: Writing RESTful Web Services

REST vs RPCURIs represent:

REST = NounsRPC = Verbs

Similar in many waysREST is more predictable

31

Page 32: Writing RESTful Web Services

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

Page 33: Writing RESTful Web Services

Other Stuff...CachingAuthorization Headers

ASP.Net Web Api 2...

33

Page 34: Writing RESTful Web Services

ConclusionsThings don’t have to be RESTful to be right

Design consistent and reliable APIs

Don’t start Bikeshedding... 34

Page 35: Writing RESTful Web Services

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

Page 36: Writing RESTful Web Services

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