51

Designing RESTful webservices and web apis

Embed Size (px)

DESCRIPTION

Whether you're building your single page application, your mobile application or just want to open up your platform to innovation one thing that you will need is well designed API and services. Learn what are the best practices and approaches in designing your REST based web services and APIs in order to create your own rock solid platforms. Presentation in Romanian at CodeCamp Iasi April, 2013

Citation preview

Page 1: Designing RESTful webservices and web apis
Page 2: Designing RESTful webservices and web apis

Occasion: Date:

Present: Classification:

Designing RESTfull WebServices and Web APIs

Best Practices

CodeCamp Iasi 20-04-2013 Remus Pereni / Software Architect / [email protected] Public

Page 3: Designing RESTful webservices and web apis

3

Software Architect TSS-Yonder Web & Mobile Web & Java Twitter: @remuspereni Web: http://remus.pereni.org

Remus Pereni

Yonder Romania http://tss-yonder.com @tssyonder Cluj Napoca

Calea Dorobantilor 18-20 Power Business Center

Iasi Sos. Pacurari 138

Page 4: Designing RESTful webservices and web apis

Evoluție  API-­‐uri  

4  

1995

De ce avem nevoie de Web

site?

2000 2005 2013

Bineinteles avem website!

Bineinteles ca avem un API!

De ce avem nevoie de API?

Page 5: Designing RESTful webservices and web apis

5  

Evoluție  API-­‐uri  

From Open APIs: State of the Market by John Musser, ProgrammableWeb

Page 6: Designing RESTful webservices and web apis

Evoluțe  API-­‐uri  

6  

From Open APIs: State of the Market by John Musser, ProgrammableWeb

Page 7: Designing RESTful webservices and web apis

REST  vs.  SOAP:  Simplicity  wins  again  

7  

Based on directory of 3,200 web APIs listed at ProgrammableWeb, May 2011

From Open APIs: State of the Market by John Musser, ProgrammableWeb

Page 8: Designing RESTful webservices and web apis

8

Componente

Page 9: Designing RESTful webservices and web apis

9

●  https://api.taskmgm.com/createCompany ●  https://api.taskmgm.com/deleteCompany ●  https://api.taskmgm.com/getCompany ●  https://api.taskmgm.com/getAllCompanies ●  https://api.taskmgm.com/getAllProjects ●  https://api.taskmgm.com/getProject ●  https://api.taskmgm.com/createProject ●  https://api.taskmgm.com/updateProject ●  https://api.taskmgm.com/deleteProject ●  https://api.taskmgm.com/createLog ●  https://api.taskmgm.com/updateLog ●  https://api.taskmgm.com/deleteLog ●  https://api.taskmgm.com/getLogs ●  https://api.taskmgm.com/getLog

Resurse Web

Page 10: Designing RESTful webservices and web apis

10

/{colecții}

conțin-> /{store-uri}

care stocheză-> /{documente}

care au datele propriuzise

Resurse Web

Page 11: Designing RESTful webservices and web apis

11

/companies

- colectie - lista de companii

/1234

- document - detalii companie 1234

Resurse Web

Page 12: Designing RESTful webservices and web apis

12

●  https://api.taskmgm.com/v1/companies ●  https://api.taskmgm.com/v1/companies/1234

●  https://api.taskmgm.com/v1/projects ●  https://api.taskmgm.com/v1/projects/1234

●  https://api.taskmgm.com/v1/logs ●  https://api.taskmgm.com/v1/logs/12182

Resurse Web

Page 13: Designing RESTful webservices and web apis

13

/projects

- colectie - lista de proiecte

/favorites

-un store -returneaza tot o listă -cu proiectele favorite

/1234

- document - detalii proiect favorit

Resurse Web

Page 14: Designing RESTful webservices and web apis

14

●  https://api.taskmgm.com/v1/projects

●  https://api.taskmgm.com/v1/projects/1234

●  https://api.taskmgm.com/v1/projects/favorites

●  https://api.taskmgm.com/v1/projects/favorites/1234

Resurse Web

Page 15: Designing RESTful webservices and web apis

15

/{colecții}

conțin-> /{store-uri}

care stocheză->

/{documente}

care au datele propriuzise

/{controlere}

modeleaza un concept procedural

Resurse Web

Page 16: Designing RESTful webservices and web apis

16

/users

- colectie - lista de utilizatori

/1234

- document - detalii unui anumit user

/resetPassword

-controler reseteaza parola

Resurse Web

Page 17: Designing RESTful webservices and web apis

17

●  https://api.taskmgm.com/v1/users

●  https://api.taskmgm.com/v1/users/1234

●  https://api.taskmgm.com/v1/users/1234/resetPassword

●  https://api.taskmgm.com/v1/users/login

Resurse Web

Page 18: Designing RESTful webservices and web apis

18

Resursă POST Crează

GET Citește

PUT Actualizează

DELETE Sterge

/companies 201 Created Crează o nouă companie

200 OK Obtine lista de companii

405 Method Not Allowed sau 200 OK Actualizeaza toată lista de companii

405 Method Not Allowed sau 200 OK Nimic sau Sterge toata lista de companii

/companies/1234

405 Method Not Allowed sau 404 Not Found

200 OK Obtine detalii despre compania 1234

200 OK Daca exista compania 1234 actualizeaza altfel erroare: 404 Not Found

200 OK Sterge compania 1234 sau 404 Not Found daca nu există

Operații asupra resurselor / Metode HTTP

Page 19: Designing RESTful webservices and web apis

19

●  RFC 3986 ●  Syntaxa unui URI e:

o scheme o "://" o authority o "/" path o [ "?" query ] o [ "#" fragment ]

●  http://example.com/v1/users#name?q=Remus

URI, definiție

Page 20: Designing RESTful webservices and web apis

20

●  Folositi substantive la plural si nu verbe o /companies o /users o /getUsers o /getCompanies

● Nu amestecati plural si singular, nu e consistent o /companies o /user o  /users

URI / Best practice-uri

Page 21: Designing RESTful webservices and web apis

21

Utilizati charactere mici in URI-uri (lowercase) ●  https://api.taskmgm.com/v1/users

o  o resursa

●  HTTP://Api.Taskmgm.com/v1/users o  aceiasi resursa ca mai sus

●  https://api.taskmgm.com/v1/Users o  o alta resursa

De ce? RFC 3896 defineste URI-urile case sensitive exceptind Protocol-ul si componentele host-ului scheme "://" authority "/" path [ "?" query ] [ "#" fragment ]

URI / Best practice-uri

Page 22: Designing RESTful webservices and web apis

22

Nu includeti extensie de fisiere in URI-uri

●  https://api.taskmgm.com/v1/users/1234.json

Mecanismele HTTP pentru negocierea continutului Headerele

o  ACCEPT o  ContentType

URI / Best practice-uri

Page 23: Designing RESTful webservices and web apis

23

●  Implicit parte din HTTP ●  header-ul: Accept  Accept                  =  "Accept"  ":"                                                  #(  media-­‐range  [  accept-­‐params  ]  )                media-­‐range        =  (  "*/*"                                                  |  (  type  "/"  "*"  )                                                  |  (  type  "/"  subtype  )                                                  )  *(  ";"  parameter  )                accept-­‐params    =  ";"  "q"  "="  qvalue  *(  accept-­‐extension  )                accept-­‐extension  =  ";"  token  [  "="  (  token  |  quoted-­‐string  )  ]  

 Accept:  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;    https://api.taskmgm.com/v1/companies?format=json  

Formate multiple

Page 24: Designing RESTful webservices and web apis

24

● Forward slash separator (/) indica relatii hierarhice o http://example.org/vinzari/2012/08/01

URI / Best practice-uri

Page 25: Designing RESTful webservices and web apis

25

●  Trailing forward slash (/) nu trebuie sa termine un URI o  http://example.org/companies/1234/ o  http://example.org/companies/1234

●  De ce? o  Nu adauga valoare semantica o  Poate cauza confuzie (2 uri-uri diferite trebuie sa

identifice 2 resurse diferite)

URI / Best practice-uri

Page 26: Designing RESTful webservices and web apis

26

Hypens (-) pot fi folosite pentru a imbunatatii readability-ul URI-urilor

http://example.org/blogs/remus-pereni/entry/primul-post

URI / Best practice-uri

Page 27: Designing RESTful webservices and web apis

27

Underscore (_) nu ar trebui folosite Link-urile de obicei sunt afisate cu underline si atuncea underscore poate fi confundat

URI / Best practice-uri

Page 28: Designing RESTful webservices and web apis

28

●  Folosit pentru a obtine starea unei resurse ●  Cererea poate contine headere dar nu

body ●  Cereri repetate la GET nu e voie sa aiba

efecte secundare / duca la modificari de stare

●  Cache-urile depind de abilitatea de a servi un raspuns fara a mai contacta serverul original

Metode HTTP / GET

Page 29: Designing RESTful webservices and web apis

29

●  Exact ca si GET, returneaza doar headerele fara body ●  Folosit la verifica existenta unei resurse sau

a metadatelor legat de ea

Metode HTTP / HEAD

Page 30: Designing RESTful webservices and web apis

30

● Folosit pentru insert si update-uri ● Mesajul trebuie sa contina o

reprezentare a resursei pe care clientul doreste sa o stocheze pe server ● Continutul mesajului poate sa nu fie

identic cu cea ce ar primi de la un request GET. Poate contine doar valorile mutabile / variabile din starea resursei ● Operatiune Idempotenta

Metode HTTP / PUT

Page 31: Designing RESTful webservices and web apis

31

●  Folosit pentru a crea o resursa noua intr-o colectie ●  Folosit pentru a invoca controleri ●  Permis pentru orice actiune fara legatura cu

repetabilitatea sau efectele colaterale (unsafe & non-idempotent) ● Nu este garantata repetabilitatea ●  A nu se folosi pentru a obtine / sterge /

actualiza resurse

Metode HTTP / POST

Page 32: Designing RESTful webservices and web apis

32

● Folosita pentru a sterge o resursa dintr-o colectie ● O data stearsa cu DELETE resursa nu

mai trebuie sa apartina colectiei (orice GET sau HEAD pe resursa respectiva trebuie sa se termine cu 404 NOT FOUND

Metode HTTP / DELETE

Page 33: Designing RESTful webservices and web apis

33

●  Folosita pentru a sterge o obtine lista de operatii posibile asupra unei resurse ●  Allow: GET, PUT, DELETE

Metode HTTP / OPTIONS

Page 34: Designing RESTful webservices and web apis

34

●  Mai multe abordari o  Versiune in path

•  http://example.com/timetrack/v1/companies/yonder o  Versiune in header

●  Versiune in header / parte din negocieri o  Un URI trebuie sa identifice constant o resursa o  Modificarea URI-ului presupune o resursa noua o  Deci V1 & V2 denota 2 resurse diferite -> Incorect

Versionarea serviciilor

Page 35: Designing RESTful webservices and web apis

35

●  Ascundeti complexitate in spate la ? o  https://api.taskmgm.com/v1/companies?limit=10&offset=0

●  Puteti folosi limit și offset ●  Să aveți valori implicite pentru ele

Paginare

Page 36: Designing RESTful webservices and web apis

36

Fie prin controller https://api.taskmgm.com/v1/companies/search

Ascundeti complexitate in spate la ?

https://api.taskmgm.com/v1/companies?search=Yonder

Cautare

Page 37: Designing RESTful webservices and web apis

37

Coduri de răspuns, tratarea exceptiilor

Http status code : 401 Unauthorized

●  { o  “developerMessage” : “Verbose, plain language description of

the problem for the app developer with hints about how to fix it.”

o  , “userMessage”:”Pass this message on to the app user if needed.”

o  , “errorCode” : 12345 o  , “more info”: http://dev.teachdogrest.com/errors/12345

●  }

Page 38: Designing RESTful webservices and web apis

38

Success Totul a funcționat

Erroare client

Aplicatia a facut ceva

greșit

Erroare server

Ups s-a intinplat

ceva aiurea

Coduri de răspuns, tratarea exceptiilor

Page 39: Designing RESTful webservices and web apis

39

●  HTTP Defineste 5 categorii

Coduri de răspuns, tratarea exceptiilor

1XX Informational Comunica informatii la nivel de protocol

2XX Success Cererea clientului acceptata cu success

3XX Redirectari Indica ca sunt nevoie actiuni suplimentare pentru a complecta requestul

4XX Errori client Erroare datorata in general request-ului / Clientului

5XX Errori server Erroare datorata in general serverului

Page 40: Designing RESTful webservices and web apis

40

Success 200 OK

Erroare client

400 Bad Reuest

Erroare server

500 Internal Server Error

Coduri de răspuns, tratarea exceptiilor

Page 41: Designing RESTful webservices and web apis

41

Coduri de răspuns, tratarea exceptiilor

Page 42: Designing RESTful webservices and web apis

42

Creare 201 Created

Resursa gresita

404 Not Found

Lipsa autorizații

401 Unauthorized

Metoda ne-

permisa 403

Forbidden

Coduri de răspuns, tratarea exceptiilor

Page 43: Designing RESTful webservices and web apis

43

●  200 (“OK”) o  Codul pe care clientii spra sa-l vada o  Indica success o  In general trebuie sa includa un raspuns in body o  Nu trebuie folosit in a comunica errori in continutul mesajului

●  201 (“Created”) o  Folosit de cite ori o colectie sau un store creaza o resursa noua

bazat pe cererea clientului o  Poate fi si raspuns al apelului unui controller in cazul in care o

resursa este creata ●  202 (“Accepted”)

o  Folosit pentru raspunsuri asincrone o  O operatiune lunga a fost inceputa, pare valida dar poate inca

genera errori o  In general folosit la controlere

Coduri de răspuns, tratarea exceptiilor

Page 44: Designing RESTful webservices and web apis

44

●  204 (“No Content”) o  Operatia e reusita dar nu exista continut de returnat (DELETE,

de exemplu) ●  301 (“Moved Permanently”)

o  Resursa s-a mutat si exista o noua locatie pentru ea o  Locatia se trimite ca parte a Location header-ului

●  303 (“See Other”) o  Controler-ul si-a terminat treaba dar in loc sa trimita un raspuns

potential nedorit poate trimite in Location un URI la o resursa care poate prezenta interes pentru clienti

●  304 (“Not Modified”) o  Similar cu 204 (“No Content) in sensul ca body-ul e gol o  Clientul are deja cea mai recenta versiune o  Folosit impreuna cu alte headere ce determina HTTP

Conditionale

Coduri de răspuns, tratarea exceptiilor

Page 45: Designing RESTful webservices and web apis

45

●  400 (“Bad Request”) o  Mesaj de erroare generic cind nici un alt 4xx nu este potrivit o  Raspunsul poate contine body cu mesaj detaliat legat de erroare

●  401 (“Unauthorized”) o  Nu are authorizarea necesara sau nu a asigurat nici un fel de

authorizare ●  403 (“Forbidden”)

o  Indica ca request-ul e corect dar backend-ul refuza sa-l onoreze o  Nu este o problema de autorizare (ar fi 401), poate clientul nu

are permisiunea de a apela acea parte din API ●  404 (“Not Found”)

o  Cererea nu poate fi mapata pe o resursa ●  405 (“Method Not Allowed”)

o  Daca clientul a incercat o operatie ne-permisa (ex: DELETE pe o resursa read only)

o  Trebuie sa se trimita inapoi header-ul Allow: GET, POST cu metodele suportate

Coduri de răspuns, tratarea exceptiilor

Page 46: Designing RESTful webservices and web apis

46

●  406 (“Not Acceptable”) o  Formatul cerut de client nu este suportat (Ex. clientul cere

application/xml prin intermediul headerului Accept dar serverul are pregatit doar application/json

●  409 (“Conflict”) o  Daca se incearca punerea unei resurse intr-o stare inconsistenta o  Ex, se incearca stergerea unei colectii care nu e goala

●  415 (“Unsuported Media Type”) o  Indica ca serverul nu poate parsa cererea in formatul descris de

header-ul Content-Type o  Ex. Body-ul contine application/xml dar serverul stie sa trateze

doar application/json ●  500 (“Internal Server Error”)

o  Probleme pe partea de server, ex exceptii aruncate si ne tratate

Coduri de răspuns, tratarea exceptiilor

Page 47: Designing RESTful webservices and web apis

47

Resurse

Web API Design? Crafting Interfaces that Developers Love

By Brian Mulloy Ebook gratuit oferit de apigee http://apigee.com/about/content/web-api-design

Page 48: Designing RESTful webservices and web apis

48

Resurse

REST API Design Rulebook Designing Consistent RESTful Web Service Interfaces By Mark Masse Publisher: O'Reilly Media Released: October 2011 Pages: 116

Page 49: Designing RESTful webservices and web apis

49

1. Atlassian REST API Design Guidelines version 1 https://developer.atlassian.com/display/DOCS/Atlassian+REST+API+Design+Guidelines+version+1

2. Thoughts on RESTful API Design Lessons learnt from designing the Red Hat Enterprise Virtualization API https://restful-api-design.readthedocs.org/en/latest/

Resurse

Page 50: Designing RESTful webservices and web apis

50

Întrebări?

photo cc by http://www.flickr.com/photos/horiavarlan/4273168957/

Page 51: Designing RESTful webservices and web apis

51

Thank You !

Please fill the evaluation form slide

photo cc by http://www.flickr.com/photos/wwworks/4759535950/