SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
REST и HATEOAS
1
REST и HATEOAS
2
Доклад не из будущего
Артём Бей
@defly_self
Fullstack dev в Trinity Mirror
3
REST != HTTP
Representational State Transfer
"Architectural Styles and
the Design of Network-based Software Architectures”
Roy Fielding
5
REST — это архитектурный
стиль для распределенных
гипермедиа систем.
6
Ресурс
http://…/resource
<xml>	
<entity/>	
</xml>
{	
entity:	{…}	
}
7
http://…/resource
<xml>	
<entity/>	
</xml>
{	
entity:	{…}	
}
представление
представление
ресурс
идентификатор
документ	
картинка	
процесс	
…
8
Richardson Maturity Model
9
REST уровня 0
POST	/api	
{	
		"do":	"createOrder",	
		"params":	{	
				"count":	2	
		}	
}	
POST	/api	
{	
		"do":	"cancelOrder",	
		"params":	{	
				"id":	"34xzfha834flksd34"	
		}	
}
200	OK	
{	
		"success":	true,	
		"res":	{	
				"id":	"f239sdk237sdf438"	
		}	
}	
200	OK	
{	
		"success":	false,	
		"error":	{	
				"code":	666,	
				"message":	"because	fk	u	thats	why"	
		}	
}	
/api
10
REST уровня 1
POST	/users	
{…}	
200	OK	
{	
		"success":	true,	
		"res":	{	
				"id":	"f239sdk237sdf438"	
		}	
}	
200	OK	
{	
		"success":	false,	
		"error":	{	
				"code":	40000,	
				"message":	"today	is		
a	bad	day"	
		}	
}	
/users
POST	/users/1	
{…}	
POST	/orders	
{…}	
/users/1
/orders
11
Tesla	Model	S	использует	REST	Level	1
REST уровня 2
13
REST уровня 2
Используем HTTP по спецификации
14
Методы
GET	
POST	
PUT	
DELETE	
OPTIONS	
HEAD	
PATCH	
…
15
16
200	OK	
{	
		"success":	false,	
		"error":	{	
				"code":	666,	
				"message":	"because	fk	u	thats	why"	
		}	
17
400	Bad	Request	
401	Unauthorized	
404	Not	Found	
402	Payment	Required	
409	Conflict	
…
18
418 I’m a teapot
19
Forbidden
Authorization:	Bearer	ToKeN
@wice_
/users	
/orders	
/profile	
…
GET	
POST	
PUT	
DELETE	
OPTIONS	
HEAD	
PATCH	
…
200	
201	
…	
300	
301	
…	
400	
401	
…	
500	
501	
…
покроет все ваши кейсы
23
REST уровень 3
24
Гипертекст
25
HATEOAS
Hypermedia As The Engine Of Application State
26
представление	ресурса	=	данные	+	контролы
27
GET	/feed	
200	OK	
{	
		"data":	[	
				{	
						"title":	"...",	
						"links":	{	
								"details":	"http://..."	
						}	
				},	
				....	
		],	
		"links":	{	
				"self":	"http://...",	
				"first":	"http://...",	
				"prev":	"http://...",	
				"next":	"http://...",	
				"last":	"http://..."	
		}	
}
28
GET	/feed?min_id=100500	
200	OK	
{	
		"data":	[	
				{	
						"title":	"...",	
						"links":	{	
								"details":	“http://..."	
						}	
				},	
				....	
		],	
		"links":	{	
				"self":	"http://...",	
				"first":	"http://...",	
				"prev":	"http://...",	
				"next":	"http://...",	
				"last":	"http://..."	
		}	
}
29
GET	/films/themartian	
200	OK	
{	
		"data":	{	
				"title":	"Марсианин",	
				"description":	"Как	Мэт	Дэймон	выращивал	картошку	на	Марсе",	
				"duration":	140,	
				"poster":	"https://s3.amazon.com/buckets/23aGd23asdsf.png"	
		},	
		"links":	{	
				"self":	“http://.../themartian”,	
				"booking":	“http://.../themartian/bookings"	
		}	
}
30
GET	/films/themartian	
200	OK	
{	
		"data":	{	
				"title":	"Марсианин",	
				"description":	"Как	Мэт	Дэймон	выращивал	картошку	на	Марсе",	
				"duration":	140,	
				"poster":	"https://s3.amazon.com/buckets/23aGd23asdsf.png"	
		},	
		"links":	{	
				"self":	“http://.../themartian”,	
"booking":	“http://.../themartian/bookings"	
		}	
}
OPTIONS	/films/themartian/bookings	
204	No	Content	
Allow:	HEAD,GET,POST,OPTIONS	
31
POST	/films/themartian/bookings	
{	
count:	3	
}	
201	Created	
Location:	http://..../bookings/1	
32
GET	/films/themartian/bookings/1	
200	OK	
{	
		"data":	{	
				"count":	3,	
				"date":	"Tue	Nov	03	2015	21:45:55	GMT+0200	(EET)",	
				"status":	"waiting"	
		},	
		"links":	{	
				"self":	"http://..../bookings/1",	
				"cancel":	"http://..../bookings/1/cancel",	
				"pay":	"http://.../bookings/1/pay"	
		}	
}
33
Стейт-машина
Переходим в новые состояния по ссылке
34
Некоторые приёмы
• Безопасные и идемпотентные операции
• Кеширование неизменяемых ресурсов
• X- заголовки
• Вендорные типы данных (

application/vnd.myapi.basket.v1+json

)
35
В чём профит?
36
Делаем клиент тоньше, не
нужно больше хачить URL
Распределённые приложения
API могут использовать роботы
Самодокументирование
Developer Experience
Вопросы к HATEOAS
42
В JSON нет ссылок и форм.
Есть спецификации:
HAL, Siren, json:api
43
Нужна ли теперь
документация?
Нужна. REST для машин.
44
Слишком академично или
много лишнего.
Не нужно реализовывать
спецификации в полном
объёме.
45
А Twitter, Facebook, … не
применяют HATEOAS.
Run-time vs Design-time
46
Почитать
• https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
• http://roy.gbiv.com/untangled/2008/rest-apis-must-be-
hypertext-driven
• http://martinfowler.com/articles/richardsonMaturityModel.html
• REST in Practice by Jim Webber, Savas Parastatidis, and Ian
Robinson
• http://www.jeffknupp.com/blog/2014/06/03/why-i-hate-hateoas
• http://timelessrepo.com/haters-gonna-hateoas
Спасибо, задавайте
вопросы!
48

Más contenido relacionado

Destacado

Securing RESTful services with Spring HATEOAS & Hdiv
Securing RESTful services with Spring HATEOAS & HdivSecuring RESTful services with Spring HATEOAS & Hdiv
Securing RESTful services with Spring HATEOAS & HdivHdiv Security
 
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...VMware Tanzu
 
Hypermedia api (HATEOAS)
Hypermedia api (HATEOAS)Hypermedia api (HATEOAS)
Hypermedia api (HATEOAS)MitinPavel
 
HCLT Whitepaper: Legacy Modernization
HCLT Whitepaper: Legacy Modernization HCLT Whitepaper: Legacy Modernization
HCLT Whitepaper: Legacy Modernization HCL Technologies
 
BPM for SOA+ESB+API and cloud
BPM for SOA+ESB+API and cloud BPM for SOA+ESB+API and cloud
BPM for SOA+ESB+API and cloud Alexander SAMARIN
 
How to become a Product Samurai - Chris Lukassen
How to become a Product Samurai - Chris LukassenHow to become a Product Samurai - Chris Lukassen
How to become a Product Samurai - Chris LukassenAvisi B.V.
 
Legacy to industry leader: a modernization case study
Legacy to industry leader: a modernization case studyLegacy to industry leader: a modernization case study
Legacy to industry leader: a modernization case studyOSSCube
 
Twilio Signal 2016 API Architecture
Twilio Signal 2016 API ArchitectureTwilio Signal 2016 API Architecture
Twilio Signal 2016 API ArchitectureTwilio Inc
 
LeaseWeb API Architecture @ APINL Meetup
LeaseWeb API Architecture @ APINL MeetupLeaseWeb API Architecture @ APINL Meetup
LeaseWeb API Architecture @ APINL MeetupRolph Haspers
 
SOA Pattern : Legacy Wrappers
SOA Pattern : Legacy Wrappers SOA Pattern : Legacy Wrappers
SOA Pattern : Legacy Wrappers WSO2
 
Updating Legacy Systems: Making the Financial Case for a Modernization Project
Updating Legacy Systems: Making the Financial Case for a Modernization Project Updating Legacy Systems: Making the Financial Case for a Modernization Project
Updating Legacy Systems: Making the Financial Case for a Modernization Project ILM Professional Services
 
IO State In Distributed API Architecture
IO State In Distributed API ArchitectureIO State In Distributed API Architecture
IO State In Distributed API ArchitectureOwen Rubel
 
Api Abstraction & Api Chaining
Api Abstraction & Api ChainingApi Abstraction & Api Chaining
Api Abstraction & Api ChainingOwen Rubel
 
Legacy modernization, cloud orchestration, api publishing
Legacy modernization, cloud orchestration, api publishingLegacy modernization, cloud orchestration, api publishing
Legacy modernization, cloud orchestration, api publishingkumar gaurav
 
Building a Modern Microservices Architecture at Gilt: The Essentials
Building a Modern Microservices Architecture at Gilt: The EssentialsBuilding a Modern Microservices Architecture at Gilt: The Essentials
Building a Modern Microservices Architecture at Gilt: The EssentialsC4Media
 
ITANA 2016: API Architecture and Implementation
ITANA 2016: API Architecture and ImplementationITANA 2016: API Architecture and Implementation
ITANA 2016: API Architecture and ImplementationColin Bell
 
Building an API Platform for Digital Transformation
Building an API Platform for Digital TransformationBuilding an API Platform for Digital Transformation
Building an API Platform for Digital TransformationWSO2
 
Dc meetup-pure-api-led-connectivity-16x9
Dc meetup-pure-api-led-connectivity-16x9Dc meetup-pure-api-led-connectivity-16x9
Dc meetup-pure-api-led-connectivity-16x9Bruce Schonk -PMP, MBA
 
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...Renaud Visage
 

Destacado (20)

Securing RESTful services with Spring HATEOAS & Hdiv
Securing RESTful services with Spring HATEOAS & HdivSecuring RESTful services with Spring HATEOAS & Hdiv
Securing RESTful services with Spring HATEOAS & Hdiv
 
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...
Modernizing the Legacy - How Dish is Adapting its SOA Services for a Cloud Fi...
 
Hypermedia api (HATEOAS)
Hypermedia api (HATEOAS)Hypermedia api (HATEOAS)
Hypermedia api (HATEOAS)
 
HCLT Whitepaper: Legacy Modernization
HCLT Whitepaper: Legacy Modernization HCLT Whitepaper: Legacy Modernization
HCLT Whitepaper: Legacy Modernization
 
BPM for SOA+ESB+API and cloud
BPM for SOA+ESB+API and cloud BPM for SOA+ESB+API and cloud
BPM for SOA+ESB+API and cloud
 
How to become a Product Samurai - Chris Lukassen
How to become a Product Samurai - Chris LukassenHow to become a Product Samurai - Chris Lukassen
How to become a Product Samurai - Chris Lukassen
 
Apiworld
ApiworldApiworld
Apiworld
 
Legacy to industry leader: a modernization case study
Legacy to industry leader: a modernization case studyLegacy to industry leader: a modernization case study
Legacy to industry leader: a modernization case study
 
Twilio Signal 2016 API Architecture
Twilio Signal 2016 API ArchitectureTwilio Signal 2016 API Architecture
Twilio Signal 2016 API Architecture
 
LeaseWeb API Architecture @ APINL Meetup
LeaseWeb API Architecture @ APINL MeetupLeaseWeb API Architecture @ APINL Meetup
LeaseWeb API Architecture @ APINL Meetup
 
SOA Pattern : Legacy Wrappers
SOA Pattern : Legacy Wrappers SOA Pattern : Legacy Wrappers
SOA Pattern : Legacy Wrappers
 
Updating Legacy Systems: Making the Financial Case for a Modernization Project
Updating Legacy Systems: Making the Financial Case for a Modernization Project Updating Legacy Systems: Making the Financial Case for a Modernization Project
Updating Legacy Systems: Making the Financial Case for a Modernization Project
 
IO State In Distributed API Architecture
IO State In Distributed API ArchitectureIO State In Distributed API Architecture
IO State In Distributed API Architecture
 
Api Abstraction & Api Chaining
Api Abstraction & Api ChainingApi Abstraction & Api Chaining
Api Abstraction & Api Chaining
 
Legacy modernization, cloud orchestration, api publishing
Legacy modernization, cloud orchestration, api publishingLegacy modernization, cloud orchestration, api publishing
Legacy modernization, cloud orchestration, api publishing
 
Building a Modern Microservices Architecture at Gilt: The Essentials
Building a Modern Microservices Architecture at Gilt: The EssentialsBuilding a Modern Microservices Architecture at Gilt: The Essentials
Building a Modern Microservices Architecture at Gilt: The Essentials
 
ITANA 2016: API Architecture and Implementation
ITANA 2016: API Architecture and ImplementationITANA 2016: API Architecture and Implementation
ITANA 2016: API Architecture and Implementation
 
Building an API Platform for Digital Transformation
Building an API Platform for Digital TransformationBuilding an API Platform for Digital Transformation
Building an API Platform for Digital Transformation
 
Dc meetup-pure-api-led-connectivity-16x9
Dc meetup-pure-api-led-connectivity-16x9Dc meetup-pure-api-led-connectivity-16x9
Dc meetup-pure-api-led-connectivity-16x9
 
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...
From a Monolithic to a Distributed API Architecture
 at Eventbrite - Presente...
 

Similar a REST и HATEOAS

!2hl++2008 Restful Architechture
!2hl++2008 Restful Architechture!2hl++2008 Restful Architechture
!2hl++2008 Restful ArchitechtureOntico
 
RESTful Architechture (Highload++ 2008)
RESTful Architechture (Highload++ 2008)RESTful Architechture (Highload++ 2008)
RESTful Architechture (Highload++ 2008)Sergey Skvortsov
 
Database (Lecture 14 – database)
Database (Lecture 14 – database)Database (Lecture 14 – database)
Database (Lecture 14 – database)Noveo
 
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...CocoaHeads
 
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)Ontico
 
Stas Sultanov "REST again? Oh, come on!"
Stas Sultanov "REST again? Oh, come on!"Stas Sultanov "REST again? Oh, come on!"
Stas Sultanov "REST again? Oh, come on!"Fwdays
 
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...Timur Shemsedinov
 
Web осень 2012 лекция 4
Web осень 2012 лекция 4Web осень 2012 лекция 4
Web осень 2012 лекция 4Technopark
 
Node.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаNode.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаAlexei Smolyanov
 
Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Vladimir Kochetkov
 
Alexander manuhin selenium_php_v2.0
Alexander manuhin selenium_php_v2.0Alexander manuhin selenium_php_v2.0
Alexander manuhin selenium_php_v2.0matroskin1980
 
React со скоростью света: не совсем обычный серверный рендеринг
React со скоростью света: не совсем обычный серверный рендерингReact со скоростью света: не совсем обычный серверный рендеринг
React со скоростью света: не совсем обычный серверный рендерингTimophy Chaptykov
 
Web and mobile development for intersystems caché, Eduard Lebedyuk
Web and mobile development for intersystems caché, Eduard LebedyukWeb and mobile development for intersystems caché, Eduard Lebedyuk
Web and mobile development for intersystems caché, Eduard LebedyukInterSystems
 
Работа с соцсетями (Lecture 19 – social)
Работа с соцсетями (Lecture 19 – social)Работа с соцсетями (Lecture 19 – social)
Работа с соцсетями (Lecture 19 – social)Noveo
 
МАИ, Сети ЭВМ, Лекция №7
МАИ, Сети ЭВМ, Лекция №7МАИ, Сети ЭВМ, Лекция №7
МАИ, Сети ЭВМ, Лекция №7Dima Dzuba
 
Building corporate portals with liferay JEEConf 2011
Building corporate portals with liferay   JEEConf 2011Building corporate portals with liferay   JEEConf 2011
Building corporate portals with liferay JEEConf 2011Alexey Kakunin
 
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человекаNETFest
 
Программируемость корпоративной сети с Cisco APIC-EM
Программируемость корпоративной сети с Cisco APIC-EMПрограммируемость корпоративной сети с Cisco APIC-EM
Программируемость корпоративной сети с Cisco APIC-EMCisco Russia
 
Mihail davidov js-ajax
Mihail davidov js-ajaxMihail davidov js-ajax
Mihail davidov js-ajaxYandex
 
Михаил Давыдов — Транспорт, Ajax
Михаил Давыдов — Транспорт, AjaxМихаил Давыдов — Транспорт, Ajax
Михаил Давыдов — Транспорт, AjaxYandex
 

Similar a REST и HATEOAS (20)

!2hl++2008 Restful Architechture
!2hl++2008 Restful Architechture!2hl++2008 Restful Architechture
!2hl++2008 Restful Architechture
 
RESTful Architechture (Highload++ 2008)
RESTful Architechture (Highload++ 2008)RESTful Architechture (Highload++ 2008)
RESTful Architechture (Highload++ 2008)
 
Database (Lecture 14 – database)
Database (Lecture 14 – database)Database (Lecture 14 – database)
Database (Lecture 14 – database)
 
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
Встреча №8. RESTful клиент — это просто. Тонкости использования RestKit, Миха...
 
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)
Консервативный Backend на Node.js / Дмитрий Ляпин (Recrumatic)
 
Stas Sultanov "REST again? Oh, come on!"
Stas Sultanov "REST again? Oh, come on!"Stas Sultanov "REST again? Oh, come on!"
Stas Sultanov "REST again? Oh, come on!"
 
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...
Примеры быстрой разработки API на масштабируемом сервере приложений Impress д...
 
Web осень 2012 лекция 4
Web осень 2012 лекция 4Web осень 2012 лекция 4
Web осень 2012 лекция 4
 
Node.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчикаNode.JS: возможности для РНР-разработчика
Node.JS: возможности для РНР-разработчика
 
Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!Взломать Web-сайт на ASP.NET? Сложно, но можно!
Взломать Web-сайт на ASP.NET? Сложно, но можно!
 
Alexander manuhin selenium_php_v2.0
Alexander manuhin selenium_php_v2.0Alexander manuhin selenium_php_v2.0
Alexander manuhin selenium_php_v2.0
 
React со скоростью света: не совсем обычный серверный рендеринг
React со скоростью света: не совсем обычный серверный рендерингReact со скоростью света: не совсем обычный серверный рендеринг
React со скоростью света: не совсем обычный серверный рендеринг
 
Web and mobile development for intersystems caché, Eduard Lebedyuk
Web and mobile development for intersystems caché, Eduard LebedyukWeb and mobile development for intersystems caché, Eduard Lebedyuk
Web and mobile development for intersystems caché, Eduard Lebedyuk
 
Работа с соцсетями (Lecture 19 – social)
Работа с соцсетями (Lecture 19 – social)Работа с соцсетями (Lecture 19 – social)
Работа с соцсетями (Lecture 19 – social)
 
МАИ, Сети ЭВМ, Лекция №7
МАИ, Сети ЭВМ, Лекция №7МАИ, Сети ЭВМ, Лекция №7
МАИ, Сети ЭВМ, Лекция №7
 
Building corporate portals with liferay JEEConf 2011
Building corporate portals with liferay   JEEConf 2011Building corporate portals with liferay   JEEConf 2011
Building corporate portals with liferay JEEConf 2011
 
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека
.NET Fest 2018. Сергей Калинец. Azure веб разработка здорового человека
 
Программируемость корпоративной сети с Cisco APIC-EM
Программируемость корпоративной сети с Cisco APIC-EMПрограммируемость корпоративной сети с Cisco APIC-EM
Программируемость корпоративной сети с Cisco APIC-EM
 
Mihail davidov js-ajax
Mihail davidov js-ajaxMihail davidov js-ajax
Mihail davidov js-ajax
 
Михаил Давыдов — Транспорт, Ajax
Михаил Давыдов — Транспорт, AjaxМихаил Давыдов — Транспорт, Ajax
Михаил Давыдов — Транспорт, Ajax
 

REST и HATEOAS