SlideShare a Scribd company logo
1 of 27
Download to read offline
1






This presentation is not about Drupal
It’s probably a bit boring: no funny images,
no code listings and a lot of text
Still here? Let’s go!

2







Brief web APIs history overview
What is web API
What is REST
How to design great web APIs
What does Drupal offer for web APIs

3
Web API is a bridge between your application
and the rest of the world
4
5
6
Is an architectural style, not a strict standard
Offers a lot of flexibility

Allows to design best practices
Provides interfaces that developers love

7
1.

2.
3.
4.
5.
6.

Write documentation
Reuse functionality of HTTP protocol
Be pragmatic
Be consistent
Be simple, hide complexity
Do not invent custom authorization method

8








Use single access point, i.e. api.example.com
There should be only 2 base URLs per
resource:
/cats
/cats/16
Be consistent: use either singular or plural
nouns
Avoid extra abstraction, use concrete names,
avoid /items, /assets etc

9






/getCat
/createCat
/getAllClients
/newVehicleCustomer







/cats
/clients
/customers
/vehicles

10




Verbs are okay:
/convert?from=UAH&to=USD&amount=100
Define this “non-resource” behavior explicitly

11
There are plenty of HTTP methods: GET, POST, PUT, DELETE, PATCH,
OPTIONS, HEAD etc
There are 4 basic operations: Create, Read, Update, Delete (CRUD)

POST => Create, GET => Read, PUT => Update, DELETE => Delete
Resource

POST

/cats
/cats/123

GET

PUT

DELETE

Create a new List cats
cat

Bulk update
cats

Delete all
cats

-

If exists,
update cat

Delete cat

Show cat

12




Deep URLs structure is a bad practice, i.e.
avoid long URLs:
/client/1/application/2/version/3/terms
Use simple approach:
/resource/identifier/resource

13




Keep base URLs structure simple
Hide all extra information behind the “?”:
◦
◦
◦
◦

Pagination
Search
Collection filtering
Partial response

14







Use HTTP status codes
Make error messages as verbose as possible
Use Warning header for any extra information
Provide debug mode (hide under the “?”)
Allow for suppressing this behavior (hide
under the “?”):
/cats?suppress_http_errors=true

15







API version number is mandatory
Use a simple ordinal number, i.e. v1, v2
Maintain at least two versions: current and
the previous one
Put version in the base URL or in the header

16







All requests should use pagination
Define defaults: number of records and offset
Define pagination: limit & offset
/cats?limit=10&offset=0
Use the same limit and offset for all resources
Allow for a partial response. Hide fields
filtering behind the “?”
/cats?fields=name,color,weight
17






Respect Accept header
Throw an error, if you cannot deliver
response in the expected format (406 Not
Acceptable)
Use JSON as a default format

18
That’s it.
Do not invent custom authorization.

Do not use oAuth-like authorization.

19
1.
2.

3.

4.

5.

Services (6.x; 7.x):
https://drupal.org/project/services
RESTful Web Services (7.x):
https://drupal.org/project/restws
Services Entity API (7.x)
http://drupal.org/project/services_entity
REST services (7.x)
https://drupal.org/sandbox/Taran2L/18073
78
REST in core (8.x)
20










Relies on the endpoints (custom URLs)
Uses drupal_form_submit() for write
operations
Out of the box covers nodes, comments,
users only
No default Drupal cookie based
authentication (requires explicit
authentication with custom hooks)
Great integration with other modules (like
Views)
21









Relies on Entity API and metadata about
entities
No endpoints: uses /entity_type/1.json or
/entity_type/1.xml
Supports any entity type out of the box
Access control on top of Entity API and Field
API
Standard user authentication over session
cookies or HTTP Basic Auth submodule

22




Combines approaches from Services and
RESTWS
Configurable endpoints + Entity API for data
management

23
?
24






Hypertext Transfer Protocol -- HTTP/1.1
http://tools.ietf.org/html/rfc2616
Web API Design
http://apigee.com/about/content/web-apidesign
REST and Serialization in Drupal 8
http://linclark.github.io/d8-rest-slides/
http://www.youtube.com/watch?v=w6dqzDb
Y78k

25
Head of Web development @ Lemberg Solutions

Taran2L
https://drupal.org/user/473438

Roman Paska
http://linkedin.com/in/romanpaska/

26
Thank you!
27

More Related Content

Viewers also liked

Артем Доценко — Deploy Plus. Better UI and more control for deploy module
Артем Доценко — Deploy Plus. Better UI and more control for deploy moduleАртем Доценко — Deploy Plus. Better UI and more control for deploy module
Артем Доценко — Deploy Plus. Better UI and more control for deploy moduleLEDC 2016
 
Олексій Калініченко — Configuration Management in Drupal8
Олексій Калініченко — Configuration Management in Drupal8Олексій Калініченко — Configuration Management in Drupal8
Олексій Калініченко — Configuration Management in Drupal8LEDC 2016
 
Олександр Лінивий — Multisite platform with continuous delivery process for m...
Олександр Лінивий — Multisite platform with continuous delivery process for m...Олександр Лінивий — Multisite platform with continuous delivery process for m...
Олександр Лінивий — Multisite platform with continuous delivery process for m...LEDC 2016
 
Андрій Юн — Воркшоп "Docker use cases for developers"
Андрій Юн — Воркшоп "Docker use cases for developers"Андрій Юн — Воркшоп "Docker use cases for developers"
Андрій Юн — Воркшоп "Docker use cases for developers"LEDC 2016
 
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...LEDC 2016
 
Ігор Карпиленко — PHPStorm for drupal developer
Ігор Карпиленко — PHPStorm for drupal developerІгор Карпиленко — PHPStorm for drupal developer
Ігор Карпиленко — PHPStorm for drupal developerLEDC 2016
 
Слава Мережко — Практикум: "Як ростити розробників"
Слава Мережко — Практикум: "Як ростити розробників"Слава Мережко — Практикум: "Як ростити розробників"
Слава Мережко — Практикум: "Як ростити розробників"LEDC 2016
 
Анатолій Поляков — Subdomains everywhere
Анатолій Поляков — Subdomains everywhereАнатолій Поляков — Subdomains everywhere
Анатолій Поляков — Subdomains everywhereLEDC 2016
 

Viewers also liked (8)

Артем Доценко — Deploy Plus. Better UI and more control for deploy module
Артем Доценко — Deploy Plus. Better UI and more control for deploy moduleАртем Доценко — Deploy Plus. Better UI and more control for deploy module
Артем Доценко — Deploy Plus. Better UI and more control for deploy module
 
Олексій Калініченко — Configuration Management in Drupal8
Олексій Калініченко — Configuration Management in Drupal8Олексій Калініченко — Configuration Management in Drupal8
Олексій Калініченко — Configuration Management in Drupal8
 
Олександр Лінивий — Multisite platform with continuous delivery process for m...
Олександр Лінивий — Multisite platform with continuous delivery process for m...Олександр Лінивий — Multisite platform with continuous delivery process for m...
Олександр Лінивий — Multisite platform with continuous delivery process for m...
 
Андрій Юн — Воркшоп "Docker use cases for developers"
Андрій Юн — Воркшоп "Docker use cases for developers"Андрій Юн — Воркшоп "Docker use cases for developers"
Андрій Юн — Воркшоп "Docker use cases for developers"
 
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...
Тарас Круц — Open Social: brand new Drupal 8 distro for building social netwo...
 
Ігор Карпиленко — PHPStorm for drupal developer
Ігор Карпиленко — PHPStorm for drupal developerІгор Карпиленко — PHPStorm for drupal developer
Ігор Карпиленко — PHPStorm for drupal developer
 
Слава Мережко — Практикум: "Як ростити розробників"
Слава Мережко — Практикум: "Як ростити розробників"Слава Мережко — Практикум: "Як ростити розробників"
Слава Мережко — Практикум: "Як ростити розробників"
 
Анатолій Поляков — Subdomains everywhere
Анатолій Поляков — Subdomains everywhereАнатолій Поляков — Subdomains everywhere
Анатолій Поляков — Subdomains everywhere
 

More from LEDC 2016

A. Postnikov & P. Mahrinsky — Drupal Community — це ми
A. Postnikov & P. Mahrinsky — Drupal Community — це миA. Postnikov & P. Mahrinsky — Drupal Community — це ми
A. Postnikov & P. Mahrinsky — Drupal Community — це миLEDC 2016
 
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...LEDC 2016
 
Андрій Поданенко — Воркшоп "Розвертання CIBox"
Андрій Поданенко — Воркшоп "Розвертання CIBox"Андрій Поданенко — Воркшоп "Розвертання CIBox"
Андрій Поданенко — Воркшоп "Розвертання CIBox"LEDC 2016
 
Юрій Герасімов — Editorial experience in Drupal8
Юрій Герасімов — Editorial experience in Drupal8Юрій Герасімов — Editorial experience in Drupal8
Юрій Герасімов — Editorial experience in Drupal8LEDC 2016
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Тарас Кирилюк — Docker basics. How-to for Drupal developers
Тарас Кирилюк — Docker basics. How-to for Drupal developersТарас Кирилюк — Docker basics. How-to for Drupal developers
Тарас Кирилюк — Docker basics. How-to for Drupal developersLEDC 2016
 
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtension
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtensionСергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtension
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtensionLEDC 2016
 
Вадим Абрамчук — Big Drupal: Issues We Met
Вадим Абрамчук — Big Drupal: Issues We MetВадим Абрамчук — Big Drupal: Issues We Met
Вадим Абрамчук — Big Drupal: Issues We MetLEDC 2016
 
Юрій Герасимов — Delayed operations with queues
Юрій Герасимов — Delayed operations with queuesЮрій Герасимов — Delayed operations with queues
Юрій Герасимов — Delayed operations with queuesLEDC 2016
 
Андрій Юн — Drupal contributor HOWTO
Андрій Юн — Drupal contributor HOWTOАндрій Юн — Drupal contributor HOWTO
Андрій Юн — Drupal contributor HOWTOLEDC 2016
 
Генадій Колтун — Перехід від фрілансера в стадію компанії
Генадій Колтун — Перехід від фрілансера в стадію компаніїГенадій Колтун — Перехід від фрілансера в стадію компанії
Генадій Колтун — Перехід від фрілансера в стадію компаніїLEDC 2016
 
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфіка
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфікаОлена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфіка
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфікаLEDC 2016
 
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студії
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студіїТарас Кирилюк та Олена Пустовойт — CI workflow у веб-студії
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студіїLEDC 2016
 
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form API
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form APIТарас Круц - Tips On Getting Everything You Can Out of Drupal Form API
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form APILEDC 2016
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zLEDC 2016
 
Андрей Поданенко - Start using Vagrant now!
Андрей Поданенко - Start using Vagrant now!Андрей Поданенко - Start using Vagrant now!
Андрей Поданенко - Start using Vagrant now!LEDC 2016
 

More from LEDC 2016 (16)

A. Postnikov & P. Mahrinsky — Drupal Community — це ми
A. Postnikov & P. Mahrinsky — Drupal Community — це миA. Postnikov & P. Mahrinsky — Drupal Community — це ми
A. Postnikov & P. Mahrinsky — Drupal Community — це ми
 
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...
Генадій Колтун — Комунізм наступає: що будемо робити, коли машини навчаться п...
 
Андрій Поданенко — Воркшоп "Розвертання CIBox"
Андрій Поданенко — Воркшоп "Розвертання CIBox"Андрій Поданенко — Воркшоп "Розвертання CIBox"
Андрій Поданенко — Воркшоп "Розвертання CIBox"
 
Юрій Герасімов — Editorial experience in Drupal8
Юрій Герасімов — Editorial experience in Drupal8Юрій Герасімов — Editorial experience in Drupal8
Юрій Герасімов — Editorial experience in Drupal8
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Тарас Кирилюк — Docker basics. How-to for Drupal developers
Тарас Кирилюк — Docker basics. How-to for Drupal developersТарас Кирилюк — Docker basics. How-to for Drupal developers
Тарас Кирилюк — Docker basics. How-to for Drupal developers
 
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtension
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtensionСергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtension
Сергій Бондаренко — Тестування Drupal сайтiв з допогою TqExtension
 
Вадим Абрамчук — Big Drupal: Issues We Met
Вадим Абрамчук — Big Drupal: Issues We MetВадим Абрамчук — Big Drupal: Issues We Met
Вадим Абрамчук — Big Drupal: Issues We Met
 
Юрій Герасимов — Delayed operations with queues
Юрій Герасимов — Delayed operations with queuesЮрій Герасимов — Delayed operations with queues
Юрій Герасимов — Delayed operations with queues
 
Андрій Юн — Drupal contributor HOWTO
Андрій Юн — Drupal contributor HOWTOАндрій Юн — Drupal contributor HOWTO
Андрій Юн — Drupal contributor HOWTO
 
Генадій Колтун — Перехід від фрілансера в стадію компанії
Генадій Колтун — Перехід від фрілансера в стадію компаніїГенадій Колтун — Перехід від фрілансера в стадію компанії
Генадій Колтун — Перехід від фрілансера в стадію компанії
 
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфіка
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфікаОлена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфіка
Олена Ольховик — Від frontend розробки до Drupal-темізації. Основи і специфіка
 
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студії
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студіїТарас Кирилюк та Олена Пустовойт — CI workflow у веб-студії
Тарас Кирилюк та Олена Пустовойт — CI workflow у веб-студії
 
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form API
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form APIТарас Круц - Tips On Getting Everything You Can Out of Drupal Form API
Тарас Круц - Tips On Getting Everything You Can Out of Drupal Form API
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
Андрей Поданенко - Start using Vagrant now!
Андрей Поданенко - Start using Vagrant now!Андрей Поданенко - Start using Vagrant now!
Андрей Поданенко - Start using Vagrant now!
 

Recently uploaded

Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426jennyeacort
 
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756dollysharma2066
 
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar HealthywayAmit Kakkar Healthyway
 
Virat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfVirat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfkigaya33
 
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncrdollysharma2066
 
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...dollysharma2066
 
'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trendsTangledThoughtsCO
 
Uttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfUttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfNoel Sergeant
 
labradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdflabradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdfAkrati jewels inc
 
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》rnrncn29
 

Recently uploaded (11)

Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝  97111⇛⇛47426
Call In girls Delhi Safdarjung Enclave/WhatsApp 🔝 97111⇛⇛47426
 
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
Call Girls 9953525677 Call Girls In Delhi Call Girls 9953525677 Call Girls In...
 
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
BOOK NIGHT-Call Girls In Noida City Centre Delhi ☎️ 8377877756
 
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
8 Easy Ways to Keep Your Heart Healthy this Summer | Amit Kakkar Healthyway
 
Virat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdfVirat Kohli Centuries In Career Age Awards and Facts.pdf
Virat Kohli Centuries In Career Age Awards and Facts.pdf
 
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
8377877756 Full Enjoy @24/7 Call Girls In Mayur Vihar Delhi Ncr
 
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
83778-876O7, Cash On Delivery Call Girls In South- EX-(Delhi) Escorts Service...
 
'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends'the Spring 2024- popular Fashion trends
'the Spring 2024- popular Fashion trends
 
Uttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdfUttoxeter & Cheadle Voice, Issue 122.pdf
Uttoxeter & Cheadle Voice, Issue 122.pdf
 
labradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdflabradorite energetic gems for well beings.pdf
labradorite energetic gems for well beings.pdf
 
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
《QUT毕业文凭网-认证昆士兰科技大学毕业证成绩单》
 

Роман Паска - RESTful webservices: вчера, сегодня, завтра.

  • 1. 1
  • 2.    This presentation is not about Drupal It’s probably a bit boring: no funny images, no code listings and a lot of text Still here? Let’s go! 2
  • 3.      Brief web APIs history overview What is web API What is REST How to design great web APIs What does Drupal offer for web APIs 3
  • 4. Web API is a bridge between your application and the rest of the world 4
  • 5. 5
  • 6. 6
  • 7. Is an architectural style, not a strict standard Offers a lot of flexibility Allows to design best practices Provides interfaces that developers love 7
  • 8. 1. 2. 3. 4. 5. 6. Write documentation Reuse functionality of HTTP protocol Be pragmatic Be consistent Be simple, hide complexity Do not invent custom authorization method 8
  • 9.     Use single access point, i.e. api.example.com There should be only 2 base URLs per resource: /cats /cats/16 Be consistent: use either singular or plural nouns Avoid extra abstraction, use concrete names, avoid /items, /assets etc 9
  • 11.   Verbs are okay: /convert?from=UAH&to=USD&amount=100 Define this “non-resource” behavior explicitly 11
  • 12. There are plenty of HTTP methods: GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD etc There are 4 basic operations: Create, Read, Update, Delete (CRUD) POST => Create, GET => Read, PUT => Update, DELETE => Delete Resource POST /cats /cats/123 GET PUT DELETE Create a new List cats cat Bulk update cats Delete all cats - If exists, update cat Delete cat Show cat 12
  • 13.   Deep URLs structure is a bad practice, i.e. avoid long URLs: /client/1/application/2/version/3/terms Use simple approach: /resource/identifier/resource 13
  • 14.   Keep base URLs structure simple Hide all extra information behind the “?”: ◦ ◦ ◦ ◦ Pagination Search Collection filtering Partial response 14
  • 15.      Use HTTP status codes Make error messages as verbose as possible Use Warning header for any extra information Provide debug mode (hide under the “?”) Allow for suppressing this behavior (hide under the “?”): /cats?suppress_http_errors=true 15
  • 16.     API version number is mandatory Use a simple ordinal number, i.e. v1, v2 Maintain at least two versions: current and the previous one Put version in the base URL or in the header 16
  • 17.      All requests should use pagination Define defaults: number of records and offset Define pagination: limit & offset /cats?limit=10&offset=0 Use the same limit and offset for all resources Allow for a partial response. Hide fields filtering behind the “?” /cats?fields=name,color,weight 17
  • 18.    Respect Accept header Throw an error, if you cannot deliver response in the expected format (406 Not Acceptable) Use JSON as a default format 18
  • 19. That’s it. Do not invent custom authorization. Do not use oAuth-like authorization. 19
  • 20. 1. 2. 3. 4. 5. Services (6.x; 7.x): https://drupal.org/project/services RESTful Web Services (7.x): https://drupal.org/project/restws Services Entity API (7.x) http://drupal.org/project/services_entity REST services (7.x) https://drupal.org/sandbox/Taran2L/18073 78 REST in core (8.x) 20
  • 21.      Relies on the endpoints (custom URLs) Uses drupal_form_submit() for write operations Out of the box covers nodes, comments, users only No default Drupal cookie based authentication (requires explicit authentication with custom hooks) Great integration with other modules (like Views) 21
  • 22.      Relies on Entity API and metadata about entities No endpoints: uses /entity_type/1.json or /entity_type/1.xml Supports any entity type out of the box Access control on top of Entity API and Field API Standard user authentication over session cookies or HTTP Basic Auth submodule 22
  • 23.   Combines approaches from Services and RESTWS Configurable endpoints + Entity API for data management 23
  • 24. ? 24
  • 25.    Hypertext Transfer Protocol -- HTTP/1.1 http://tools.ietf.org/html/rfc2616 Web API Design http://apigee.com/about/content/web-apidesign REST and Serialization in Drupal 8 http://linclark.github.io/d8-rest-slides/ http://www.youtube.com/watch?v=w6dqzDb Y78k 25
  • 26. Head of Web development @ Lemberg Solutions Taran2L https://drupal.org/user/473438 Roman Paska http://linkedin.com/in/romanpaska/ 26