1
 Anton Bogdan 
◦ Architect in Softengi company 
◦ Enviance team 
 29 years old 
2
Representational 
State 
Transfer 
3 
is a software 
architectural style
2000 by Roy Fielding in his doctoral 
dissertation at UC Irvine 
4
 Client–server 
 Stateless 
 Cacheable 
 Layered system 
5
 Uniform interface 
◦ Identification of resources (URI) 
◦ Manipulation of resources through these 
representations 
◦ Self-descriptive messages 
◦ Hypermedia as the engine of application 
state (A.K.A. HATEOAS) 
6
Then you will get: 
Performance, scalability, simplicity, 
modifiability, visibility, portability, and 
reliability. 
7
8
9
 POST /appointmentService.asmx 
◦ <openSlotRequest date = "2010-01-04" doctor = 
"mjones"/> 
 HTTP/1.1 200 OK 
◦ <openSlotList> 
◦ <slot start = "1400" end = "1450“ status=“open”> 
◦ <doctor id = "mjones"/> 
◦ </slot> 
◦ <slot start = "1600" end = "1650“ status=“booked”> 
◦ <doctor id = "mjones"/> 
◦ </slot> 
◦ </openSlotList> 
10
 POST /doctors/mjones/appointments/ 
◦ <openSlotRequest date = "2010-01-04“/> 
 HTTP/1.1 200 OK 
◦ <openSlotList> 
◦ <slot start = "1400" end = "1450“ status=“open”/> 
◦ <slot start = "1600" end = "1650“ status=“booked”/> 
◦ </openSlotList> 
11
 GET /doctors/mjones/appointments/?date=20100104 
 HTTP/1.1 200 OK 
◦ <openSlotList> 
◦ <slot start = "1400" end = "1450“ status=“open”/> 
◦ <slot start = "1600" end = "1650“ status=“booked”/> 
◦ </openSlotList> 
12
 GET /doctors/mjones/appointments/?date=20100104 
 HTTP/1.1 200 OK 
<openSlotList> 
<slot start = "1400" end = "1450“ status=“open”> 
<link rel=“slots/book” uri=“1400”/> 
<slot/> 
<slot start = "1600" end = "1650“ status=“booked”> 
<link rel=“slots/move” uri=“1600”/> 
<link rel=“slots/cancel” uri=“1600”/> 
<slot/> 
</openSlotList> 
13
 It’s very hard to be fully REST-style 
compatible. 
 Most of modern REST API implementations 
(Flickr api, Twitter api, Google calendar api) 
are just Level 1 and Level 2. 
 Specs based on REST: 
◦ WebDav protocol 
◦ Odata protocol (designed for Entity Framework) 
14
15
◦ /workflows/ 
◦ /workflows/<workflow Id>/ - bad 
◦ /workflows/<workflow Id>-<workflow Name>/ - good 
◦ /workflows/<workflow Name>/ - okay 
16
 Permanent. Should not be changed with time. 
 No special chars or file extensions (.php, 
.aspx) if they are not meaningful. 
 Context friendly. 
◦ /users/current/details 
 vs. /users/user-anton/details 
◦ /forecasts/cambridge/today 
 may redirects to, say, /forecasts/cambridge/2009-04-26 
17
 URI should be human readable and easily guessed. 
 Each part should be meaningful. All URI parts together should be 
good nested, and help visualize the site structure. 
◦ /cars/alfa-romeos/gt 
 Nouns, not verbs. 
 Resource Names: prefer to use lower-case and hyphen instead of 
spaces. 
◦ /tasks/by-a-new-car 
 Resource IDs: prefer to use additional meaning prefix. 
◦ /tasks/task-17 
◦ /conversations/conversation-{id}/todo-list-{id}/todo-{id} 
18
 /workflows/ 
◦ GET – Get a list (?) 
◦ POST - Create 
 201 (Created), Location:<new url> 
 /workflows/SomeItem 
◦ GET - Read 
◦ PUT - Update 
◦ DELETE - Delete 
◦ PATCH – Partial update 
19
You should introduce your own WEB-Methods. 
Examples: 
 /workflows/SomeItem 
 <OPERATION> - Non-standard operations 
 BOOK 
 BUY 
 CALCULATE 
 LOCK 
 RENT 
 … .etc 
from WebDav: 
 /workflows/SomeItem 
 MOVE 
 Destination: <new url> 
 COPY 
 Destination: <new url> 
20
 /workflows/SomeItem/<operation> 
 POST - Non-standard operations 
21
 Less Db identifiers 
 More names and URLs 
 Human readable 
 No .Net/Java specifics: 
◦ type: “MyNamespace.Workflow” 
 URL for hierarchies 
 WebDav - for file systems. 
◦ 
22
 No complex inner structures : 
◦ “name”: “Object name” 
◦ “userfields”: [ 
 { 
 Id:17, 
 name: “Permissions” 
 type: “list of checkboxes” 
 Value: [ 
 {“id”:24, “value” “Open allowed” } 
 {“id”:28, “value” “Close allowed” } 
 ] 
 } 
◦ ] 
 Keep all simple and human readable: 
◦ “name”: “Object name” 
◦ “Permissions”: [“Open allowed”, “Close allowed”] (! manual serialization may be required) 
23
24
 Option #1: URL 
/workflows/?name=My&date=2007 
25
 Option #2: Advanced URI 
/workflows/ 
?date=[MORE]2007 (?date=<2007) 
?name=[LIKE]Jo 
?name=[LIST]Jo,Mary,Anton, 
?type.name=Lab1 
?[order]=name,date 
?[fields]=id,name 
26
 Odata 
◦ service.svc/Posts?$filter=OwnerUserId eq 209 
◦ service.svc/Users?$filter=substringof('SQL',Title) or substringof('sql-server', 
Tags)&$format=json 
 Mongo 
◦ db/collections/?filter_type=cluster&filter_id=1&limit=-10 
 Gdata 
◦ /feeds?fields=link,entry(@gd:etag,id,updated,link[@rel='edit'])) 
 restSQL 
◦ /restsql/res/Actor?first_name=JULIANNE&last_name=DENCH&_limit=10&_offset=0 
27
 Option #3: SQL 
◦ Separate functionality 
◦ Require of supporting public schema & security! 
◦/sql?q=SELECT * FROM 
workflows WHERE name=My 
AND type=system AND date < 
2007&page=1&pagesize=20 
28
/sql?q=SELECT … 
SELECT * 
FROM workflows 
WHERE name=My AND type=system AND date < 2007 
Parsing 
Validating 
Transforming 
Paging 
SELECT TOP 20 w.id, w.name, w.type, cfv.[Field1] 
FROM workflows w 
INNER JOIN permissions p 
ON p.id = p.objectId AND p.userId= <userId> 
INNER JOIN customfieldvalue cfv 
ON p.id = cfv.objectId AND cfv.name = “Field1” 
WHERE name=My AND type=system AND date < 2007 
29
 Send user-password with each request (like 
Basic authentication) 
◦ REST-way style 
◦ Not always practical 
 Session ID in header (implemented) 
◦ Authorization: RESTAPI realm=“<Session ID>” 
 Auth. Cookie (implemented) 
 Auth. Cookie of main Web UI (implemented) 
30
 By URL 
◦ api/ver1/* 
 By header 
◦ X-Rest-Api-Version: 1 
 By mime-type 
◦ Accept: application/vnd.restapiv1+json; 
◦ Accept: application/vnd.restapi+json; version=1; 
31
 Error Codes 
◦ 400 – Bad request (wrong json, ValidationException) 
◦ 401 – Unauthorized (no Session ID) 
◦ 404 – Not Found - ObjectDoesNotExistException 
◦ 409 – Conflict - ObjectAlreadyExistException 
◦ 500 – Unexpected, unknown error 
◦ 503 – Service Unavailable 
 SQL timeout 
 Request limit 
 Retry-After: <seconds> 
 Error Meta: 
error:{ 
errorNumber: 500 
message: “” 
stacktrace: “<for dev only>” 
} 
32
33
 SOAP 
 /Auth.asmx 
 /Workflows.asmx 
 /Tasks.asmx 
 REST 
 /sessions/ 
 /processes/workflows/ 
 /processes/tasks/ 
34
 Well defined standard 
 Complex format 
 Meta Describer: WSDL 
 Not intended to be human readable 
 Excellent support in most IDEs (stub 
generation) 
 Hard to call from JavaScript 
 Each service – separate and independent item 
◦ Auth.asmx 
◦ Workflow.asmx 
35
 Not standardized - is a style 
 Conforms to REST style 
 Lead to design human readable API: 
◦ URL, names, serialized types 
 Bad support in most IDEs (problems with subs 
generation) 
 Easy to call from JavaScript 
 Popular 
 Each service are not separate – solid api: 
◦ /sessions/ 
◦ /processes/workflows/ 
◦ /processes/tasks/ 
36
 REST – it’s not spec, it’s architectural style 
◦ It’s an art! 
 Leverage HTTP! 
 URL, Headers, Mime, Accepts 
 Human readable URLs, XML and JSON ! 
37
38
 http://xpinjection.com/2012/06/14/rest-in-uadevclub-july-5/ 
 http://video.yandex.ua/users/xpinjection/view/192/ 
 http://video.yandex.ua/users/xpinjection/view/193/ 
 http://video.yandex.ua/users/xpinjection/view/194/ 
 http://martinfowler.com/articles/richardsonMaturityModel.html 
 http://www.iana.org/time-zones 
 http://www.w3.org/TR/cors/ 
 https://developers.google.com/gdata/docs/2.0/reference#Partia 
lResponse 
 http://www.mongodb.org/display/DOCS/Advanced+Queries 
 http://restsql.org/doc/ref/index.html 
 http://www.hanselman.com/blog/CreatingAnODataAPIForStackO 
verflowIncludingXMLAndJSONIn30Minutes.aspx 
 Libs: 
◦ http://easyxdm.net/wp/ 
◦ https://github.com/bigeasy/timezone 
39

About REST. Архитектурные семинары Softengi

  • 1.
  • 2.
     Anton Bogdan ◦ Architect in Softengi company ◦ Enviance team  29 years old 2
  • 3.
    Representational State Transfer 3 is a software architectural style
  • 4.
    2000 by RoyFielding in his doctoral dissertation at UC Irvine 4
  • 5.
     Client–server Stateless  Cacheable  Layered system 5
  • 6.
     Uniform interface ◦ Identification of resources (URI) ◦ Manipulation of resources through these representations ◦ Self-descriptive messages ◦ Hypermedia as the engine of application state (A.K.A. HATEOAS) 6
  • 7.
    Then you willget: Performance, scalability, simplicity, modifiability, visibility, portability, and reliability. 7
  • 8.
  • 9.
  • 10.
     POST /appointmentService.asmx ◦ <openSlotRequest date = "2010-01-04" doctor = "mjones"/>  HTTP/1.1 200 OK ◦ <openSlotList> ◦ <slot start = "1400" end = "1450“ status=“open”> ◦ <doctor id = "mjones"/> ◦ </slot> ◦ <slot start = "1600" end = "1650“ status=“booked”> ◦ <doctor id = "mjones"/> ◦ </slot> ◦ </openSlotList> 10
  • 11.
     POST /doctors/mjones/appointments/ ◦ <openSlotRequest date = "2010-01-04“/>  HTTP/1.1 200 OK ◦ <openSlotList> ◦ <slot start = "1400" end = "1450“ status=“open”/> ◦ <slot start = "1600" end = "1650“ status=“booked”/> ◦ </openSlotList> 11
  • 12.
     GET /doctors/mjones/appointments/?date=20100104  HTTP/1.1 200 OK ◦ <openSlotList> ◦ <slot start = "1400" end = "1450“ status=“open”/> ◦ <slot start = "1600" end = "1650“ status=“booked”/> ◦ </openSlotList> 12
  • 13.
     GET /doctors/mjones/appointments/?date=20100104  HTTP/1.1 200 OK <openSlotList> <slot start = "1400" end = "1450“ status=“open”> <link rel=“slots/book” uri=“1400”/> <slot/> <slot start = "1600" end = "1650“ status=“booked”> <link rel=“slots/move” uri=“1600”/> <link rel=“slots/cancel” uri=“1600”/> <slot/> </openSlotList> 13
  • 14.
     It’s veryhard to be fully REST-style compatible.  Most of modern REST API implementations (Flickr api, Twitter api, Google calendar api) are just Level 1 and Level 2.  Specs based on REST: ◦ WebDav protocol ◦ Odata protocol (designed for Entity Framework) 14
  • 15.
  • 16.
    ◦ /workflows/ ◦/workflows/<workflow Id>/ - bad ◦ /workflows/<workflow Id>-<workflow Name>/ - good ◦ /workflows/<workflow Name>/ - okay 16
  • 17.
     Permanent. Shouldnot be changed with time.  No special chars or file extensions (.php, .aspx) if they are not meaningful.  Context friendly. ◦ /users/current/details  vs. /users/user-anton/details ◦ /forecasts/cambridge/today  may redirects to, say, /forecasts/cambridge/2009-04-26 17
  • 18.
     URI shouldbe human readable and easily guessed.  Each part should be meaningful. All URI parts together should be good nested, and help visualize the site structure. ◦ /cars/alfa-romeos/gt  Nouns, not verbs.  Resource Names: prefer to use lower-case and hyphen instead of spaces. ◦ /tasks/by-a-new-car  Resource IDs: prefer to use additional meaning prefix. ◦ /tasks/task-17 ◦ /conversations/conversation-{id}/todo-list-{id}/todo-{id} 18
  • 19.
     /workflows/ ◦GET – Get a list (?) ◦ POST - Create  201 (Created), Location:<new url>  /workflows/SomeItem ◦ GET - Read ◦ PUT - Update ◦ DELETE - Delete ◦ PATCH – Partial update 19
  • 20.
    You should introduceyour own WEB-Methods. Examples:  /workflows/SomeItem  <OPERATION> - Non-standard operations  BOOK  BUY  CALCULATE  LOCK  RENT  … .etc from WebDav:  /workflows/SomeItem  MOVE  Destination: <new url>  COPY  Destination: <new url> 20
  • 21.
     /workflows/SomeItem/<operation> POST - Non-standard operations 21
  • 22.
     Less Dbidentifiers  More names and URLs  Human readable  No .Net/Java specifics: ◦ type: “MyNamespace.Workflow”  URL for hierarchies  WebDav - for file systems. ◦ 22
  • 23.
     No complexinner structures : ◦ “name”: “Object name” ◦ “userfields”: [  {  Id:17,  name: “Permissions”  type: “list of checkboxes”  Value: [  {“id”:24, “value” “Open allowed” }  {“id”:28, “value” “Close allowed” }  ]  } ◦ ]  Keep all simple and human readable: ◦ “name”: “Object name” ◦ “Permissions”: [“Open allowed”, “Close allowed”] (! manual serialization may be required) 23
  • 24.
  • 25.
     Option #1:URL /workflows/?name=My&date=2007 25
  • 26.
     Option #2:Advanced URI /workflows/ ?date=[MORE]2007 (?date=<2007) ?name=[LIKE]Jo ?name=[LIST]Jo,Mary,Anton, ?type.name=Lab1 ?[order]=name,date ?[fields]=id,name 26
  • 27.
     Odata ◦service.svc/Posts?$filter=OwnerUserId eq 209 ◦ service.svc/Users?$filter=substringof('SQL',Title) or substringof('sql-server', Tags)&$format=json  Mongo ◦ db/collections/?filter_type=cluster&filter_id=1&limit=-10  Gdata ◦ /feeds?fields=link,entry(@gd:etag,id,updated,link[@rel='edit']))  restSQL ◦ /restsql/res/Actor?first_name=JULIANNE&last_name=DENCH&_limit=10&_offset=0 27
  • 28.
     Option #3:SQL ◦ Separate functionality ◦ Require of supporting public schema & security! ◦/sql?q=SELECT * FROM workflows WHERE name=My AND type=system AND date < 2007&page=1&pagesize=20 28
  • 29.
    /sql?q=SELECT … SELECT* FROM workflows WHERE name=My AND type=system AND date < 2007 Parsing Validating Transforming Paging SELECT TOP 20 w.id, w.name, w.type, cfv.[Field1] FROM workflows w INNER JOIN permissions p ON p.id = p.objectId AND p.userId= <userId> INNER JOIN customfieldvalue cfv ON p.id = cfv.objectId AND cfv.name = “Field1” WHERE name=My AND type=system AND date < 2007 29
  • 30.
     Send user-passwordwith each request (like Basic authentication) ◦ REST-way style ◦ Not always practical  Session ID in header (implemented) ◦ Authorization: RESTAPI realm=“<Session ID>”  Auth. Cookie (implemented)  Auth. Cookie of main Web UI (implemented) 30
  • 31.
     By URL ◦ api/ver1/*  By header ◦ X-Rest-Api-Version: 1  By mime-type ◦ Accept: application/vnd.restapiv1+json; ◦ Accept: application/vnd.restapi+json; version=1; 31
  • 32.
     Error Codes ◦ 400 – Bad request (wrong json, ValidationException) ◦ 401 – Unauthorized (no Session ID) ◦ 404 – Not Found - ObjectDoesNotExistException ◦ 409 – Conflict - ObjectAlreadyExistException ◦ 500 – Unexpected, unknown error ◦ 503 – Service Unavailable  SQL timeout  Request limit  Retry-After: <seconds>  Error Meta: error:{ errorNumber: 500 message: “” stacktrace: “<for dev only>” } 32
  • 33.
  • 34.
     SOAP /Auth.asmx  /Workflows.asmx  /Tasks.asmx  REST  /sessions/  /processes/workflows/  /processes/tasks/ 34
  • 35.
     Well definedstandard  Complex format  Meta Describer: WSDL  Not intended to be human readable  Excellent support in most IDEs (stub generation)  Hard to call from JavaScript  Each service – separate and independent item ◦ Auth.asmx ◦ Workflow.asmx 35
  • 36.
     Not standardized- is a style  Conforms to REST style  Lead to design human readable API: ◦ URL, names, serialized types  Bad support in most IDEs (problems with subs generation)  Easy to call from JavaScript  Popular  Each service are not separate – solid api: ◦ /sessions/ ◦ /processes/workflows/ ◦ /processes/tasks/ 36
  • 37.
     REST –it’s not spec, it’s architectural style ◦ It’s an art!  Leverage HTTP!  URL, Headers, Mime, Accepts  Human readable URLs, XML and JSON ! 37
  • 38.
  • 39.
     http://xpinjection.com/2012/06/14/rest-in-uadevclub-july-5/ http://video.yandex.ua/users/xpinjection/view/192/  http://video.yandex.ua/users/xpinjection/view/193/  http://video.yandex.ua/users/xpinjection/view/194/  http://martinfowler.com/articles/richardsonMaturityModel.html  http://www.iana.org/time-zones  http://www.w3.org/TR/cors/  https://developers.google.com/gdata/docs/2.0/reference#Partia lResponse  http://www.mongodb.org/display/DOCS/Advanced+Queries  http://restsql.org/doc/ref/index.html  http://www.hanselman.com/blog/CreatingAnODataAPIForStackO verflowIncludingXMLAndJSONIn30Minutes.aspx  Libs: ◦ http://easyxdm.net/wp/ ◦ https://github.com/bigeasy/timezone 39

Editor's Notes

  • #2 Кто не слышал про REST? Кто не только слышал но и знает что такое рест?
  • #4 Может для кого-то это будет сюрпризом - REST это не вебсерсисы, это не спецификация - это архитектурный стиль распределенных систем.
  • #5 Понятие REST ввел Рой Филдинг в своей докторской диссертации. Он является одним из авторов HTTP и URI. Он выделил определенный стиль или подход распределенной системы WWW, и назвал его REST.
  • #6 Если распределенная система хочет хочет следовать REST стилю - то она должна выполяться следующие требования.
  • #8 Взамен выполнения таких требований - общая стоимость системы понизиться. Также, у такой системы легко достичь следующих важных качеств: Быстродействие, маштабирование, расширяемость, доступность, отказоустойчивость, гипкость.
  • #9 Сейчас давайте перейдем к практическому примеру применения REST - в Web Services. До этого мы говорили что WWW уже следует rest стилю. Web Sevices обычно базируються на WWW, так в чем же отличие? Отличие заключаеться в том что распределенная система может использовать элементы WWW (HTTP) как, к примеру, транспорт и при этом НЕ следовать REST. Так делают SOAP WebServices. Потому, для выявления уровня соответсвия системы REST стилю - существует так называемая "Модель Зрелости Ричардсона".
  • #10 Вот она на илюстрации. Зачастую её используют для определения соответствия Web-Services REST стилю. Тоесть далее мы будем илюстрировать примеры на уровне HTTP протокола.
  • #11 На нулевом уровне - мы используем HTTP как транспорт. Так обычно поступает SOAP, также он может использовать и другой транспорт - smpt, даже UPD тд. На примере не показано но даже в самом XML сообщении есть и место для хедеров, HTTP хедеры не используються.
  • #12 Здесь мы вводим адресацию, использую URL.
  • #13 Здесь мы начинаем использовать HTTP Methods - например, GET - для Readonly и POST для остальных. Это уже дает возможно кеширования на уровне сервера, прокси-сервера или клиента.
  • #14 Здесь мы добавляем hyper-text. В данном случае - для избавления клиента от необходимости строить URL, перемещая логику на сервер.
  • #15 Большинство существующих вебсервисов имеет 1 или 2 уровень. Хорошими примерами успешного примения REST стиля в Webservices можно считать спецификации WebDav. и к примеру ODATA. О них по -позже.