SlideShare a Scribd company logo
Best Practices for
Designing a Pragmatic
RESTful API
Key requirements for the API
• It should use web standards where they make
sense
• It should be simple, intuitive and consistent
• It should be efficient, while maintaining balance
with the other requirements
The key principles of REST involve separating
your API into logical resources.
These resources are manipulated using HTTP
requests where the method (GET, POST,
PUT, PATCH, DELETE) has specific meaning.
RESTful principles provide strategies to handle CRUD
actions using HTTP methods mapped as follows:
• GET /tickets - Retrieves a list of tickets
• GET /tickets/12 - Retrieves a specific ticket
• POST /tickets - Creates a new ticket
• PUT /tickets/12 - Updates ticket #12
• PATCH /tickets/12 - Partially updates ticket #12
• DELETE /tickets/12 - Deletes ticket #12
There are no method naming
conventions to follow and the URL structure
is clean & clear.
But how do you deal with
relations?
• GET /tickets/12/messages - Retrieves list of messages for ticket
#12
• GET /tickets/12/messages/5 - Retrieves message #5 for ticket #12
• POST /tickets/12/messages - Creates a new message in ticket
#12
• PUT /tickets/12/messages/5 - Updates message #5 for ticket #12
• PATCH /tickets/12/messages/5 - Partially updates message #5 for
ticket #12
• DELETE /tickets/12/messages/5 - Deletes message #5 for ticket
#12
What about actions that
don't fit into the world of
CRUD operations?
• An activate action could be mapped to a boolean
activated field and updated via a PATCH to the
resource
• PUT /gists/:id/star and DELETE /gists/:id/star
• Just do what's right from the perspective of the
API consumer and make sure it's documented
clearly
• SSL
• Documentation
• Versioning
Result filtering, sorting &
searching
• GET /tickets?state=open - query parameter that
implements a filter
• GET /tickets?sort=-priority - Retrieves a list of
tickets in descending order of priority
• GET /tickets?q=return&state=open&sort=-
priority,created_at - Retrieve the highest priority
open tickets mentioning the word 'return'
Updates & creation
should return a resource
representation
JSON only responses
An API that accepts JSON encoded POST, PUT & PATCH requests should
also require the Content-Type header be set to application/json or throw a
415 Unsupported Media Type HTTP status code.
JSON encoded POST, PUT & PATCH bodies
snake_case vs camelCase
Rate limiting
• X-Rate-Limit-Limit - The number of allowed
requests in the current period
• X-Rate-Limit-Remaining - The number of
remaining requests in the current period
• X-Rate-Limit-Reset - The number of seconds left
in the current period
Errors
HTTP status codes
• 200 OK - Response to a successful GET, PUT,
PATCH or DELETE. Can also be used for a
POST that doesn't result in a creation.
• 201 Created - Response to a POST that results
in a creation. Should be combined with a
Location header pointing to the location of the
new resource
• 204 No Content - Response to a successful
request that won't be returning a body (like a
DELETE request)
• 400 Bad Request - The request is malformed,
such as if the body does not parse
• 401 Unauthorized - When no or invalid
authentication details are provided. Also useful to
trigger an auth popup if the API is used from a
browser
• 403 Forbidden - When authentication succeeded
but authenticated user doesn't have access to
the resource
• 404 Not Found - When a non-existent resource is
requested
• 405 Method Not Allowed - When an HTTP
method is being requested that isn't allowed for
the authenticated user
• 429 Too Many Requests - When a request is
rejected due to rate limiting
THX
https://fractal.thephpleague.com
https://clockwise.software/blog/
https://twitter.com/bodva

More Related Content

What's hot

REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
Ashok Pundit
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
mwinteringham
 
REST API Design
REST API DesignREST API Design
REST API Design
Devi Kiran G
 
Demystify Salesforce Bulk API
Demystify Salesforce Bulk APIDemystify Salesforce Bulk API
Demystify Salesforce Bulk API
Dhanik Sahni
 
What is an API?
What is an API?What is an API?
What is an API?
Muhammad Zuhdi
 
Rest API
Rest APIRest API
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
apidays
 
40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently
postmanclient
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
Andrey Oleynik
 
Knowledge of web ui for automation testing
Knowledge  of web ui for automation testingKnowledge  of web ui for automation testing
Knowledge of web ui for automation testing
Artem Korchevyi
 
API Basics
API BasicsAPI Basics
API Basics
Ritul Chaudhary
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
Lorna Mitchell
 
L18 REST API Design
L18 REST API DesignL18 REST API Design
L18 REST API Design
Ólafur Andri Ragnarsson
 
Test in Rest. API testing with the help of Rest Assured.
Test in Rest. API testing with the help of  Rest Assured.Test in Rest. API testing with the help of  Rest Assured.
Test in Rest. API testing with the help of Rest Assured.
Artem Korchevyi
 
Web API testing : A quick glance
Web API testing : A quick glanceWeb API testing : A quick glance
Web API testing : A quick glance
Dhanalaxmi K
 
Clean up this mess - API Gateway & Service Discovery in .NET
Clean up this mess - API Gateway & Service Discovery in .NETClean up this mess - API Gateway & Service Discovery in .NET
Clean up this mess - API Gateway & Service Discovery in .NET
Marcin Tyborowski
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
Restlet
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
Suraj Gupta
 
Aws Technical Day 2015 - Amazon API Gateway
Aws Technical Day 2015 - Amazon API GatewayAws Technical Day 2015 - Amazon API Gateway
Aws Technical Day 2015 - Amazon API Gateway
aws-marketing-il
 

What's hot (20)

REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
 
REST API Design
REST API DesignREST API Design
REST API Design
 
Demystify Salesforce Bulk API
Demystify Salesforce Bulk APIDemystify Salesforce Bulk API
Demystify Salesforce Bulk API
 
What is an API?
What is an API?What is an API?
What is an API?
 
Rest API
Rest APIRest API
Rest API
 
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
apidays LIVE India - REST the Events - REST APIs for Event-Driven Architectur...
 
40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
Knowledge of web ui for automation testing
Knowledge  of web ui for automation testingKnowledge  of web ui for automation testing
Knowledge of web ui for automation testing
 
API Basics
API BasicsAPI Basics
API Basics
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
 
L18 REST API Design
L18 REST API DesignL18 REST API Design
L18 REST API Design
 
Test in Rest. API testing with the help of Rest Assured.
Test in Rest. API testing with the help of  Rest Assured.Test in Rest. API testing with the help of  Rest Assured.
Test in Rest. API testing with the help of Rest Assured.
 
Web API testing : A quick glance
Web API testing : A quick glanceWeb API testing : A quick glance
Web API testing : A quick glance
 
Clean up this mess - API Gateway & Service Discovery in .NET
Clean up this mess - API Gateway & Service Discovery in .NETClean up this mess - API Gateway & Service Discovery in .NET
Clean up this mess - API Gateway & Service Discovery in .NET
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Aws Technical Day 2015 - Amazon API Gateway
Aws Technical Day 2015 - Amazon API GatewayAws Technical Day 2015 - Amazon API Gateway
Aws Technical Day 2015 - Amazon API Gateway
 

Similar to REST API V2

Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIs
amesar0
 
A Look at OData
A Look at ODataA Look at OData
A Look at OData
Woodruff Solutions LLC
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
Mario Cardinal
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
Jeelani Shaik
 
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
Jitendra Bafna
 
Graph ql vs rest
Graph ql vs restGraph ql vs rest
Graph ql vs rest
Mihai Enescu
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
API testing with the help of Rest Assured
API testing with the help of  Rest Assured API testing with the help of  Rest Assured
API testing with the help of Rest Assured
Artem Korchevyi
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
Muhammad Aamir ...
 
Api design and development
Api design and developmentApi design and development
Api design and development
oquidave
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
Maýur Chourasiya
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Christopher Bartling
 
Attacking REST API
Attacking REST APIAttacking REST API
Attacking REST API
Siddharth Bezalwar
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
Obaidur (OB) Rashid
 
POSTMAN.pptx
POSTMAN.pptxPOSTMAN.pptx
POSTMAN.pptx
RamaKrishna970827
 
Apex REST
Apex RESTApex REST
Apex REST
Boris Bachovski
 
The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016
Restlet
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
Tharindu Weerasinghe
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service
BIOVIA
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
Mahek Merchant
 

Similar to REST API V2 (20)

Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIs
 
A Look at OData
A Look at ODataA Look at OData
A Look at OData
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
 
Graph ql vs rest
Graph ql vs restGraph ql vs rest
Graph ql vs rest
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
API testing with the help of Rest Assured
API testing with the help of  Rest Assured API testing with the help of  Rest Assured
API testing with the help of Rest Assured
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
 
Api design and development
Api design and developmentApi design and development
Api design and development
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Attacking REST API
Attacking REST APIAttacking REST API
Attacking REST API
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
POSTMAN.pptx
POSTMAN.pptxPOSTMAN.pptx
POSTMAN.pptx
 
Apex REST
Apex RESTApex REST
Apex REST
 
The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016The never-ending REST API design debate -- Devoxx France 2016
The never-ending REST API design debate -- Devoxx France 2016
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
(ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service (ATS6-PLAT04) Query service
(ATS6-PLAT04) Query service
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 

Recently uploaded

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 

Recently uploaded (20)

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 

REST API V2

  • 1. Best Practices for Designing a Pragmatic RESTful API
  • 2. Key requirements for the API • It should use web standards where they make sense • It should be simple, intuitive and consistent • It should be efficient, while maintaining balance with the other requirements
  • 3. The key principles of REST involve separating your API into logical resources. These resources are manipulated using HTTP requests where the method (GET, POST, PUT, PATCH, DELETE) has specific meaning.
  • 4. RESTful principles provide strategies to handle CRUD actions using HTTP methods mapped as follows: • GET /tickets - Retrieves a list of tickets • GET /tickets/12 - Retrieves a specific ticket • POST /tickets - Creates a new ticket • PUT /tickets/12 - Updates ticket #12 • PATCH /tickets/12 - Partially updates ticket #12 • DELETE /tickets/12 - Deletes ticket #12
  • 5. There are no method naming conventions to follow and the URL structure is clean & clear.
  • 6. But how do you deal with relations?
  • 7. • GET /tickets/12/messages - Retrieves list of messages for ticket #12 • GET /tickets/12/messages/5 - Retrieves message #5 for ticket #12 • POST /tickets/12/messages - Creates a new message in ticket #12 • PUT /tickets/12/messages/5 - Updates message #5 for ticket #12 • PATCH /tickets/12/messages/5 - Partially updates message #5 for ticket #12 • DELETE /tickets/12/messages/5 - Deletes message #5 for ticket #12
  • 8. What about actions that don't fit into the world of CRUD operations?
  • 9. • An activate action could be mapped to a boolean activated field and updated via a PATCH to the resource • PUT /gists/:id/star and DELETE /gists/:id/star • Just do what's right from the perspective of the API consumer and make sure it's documented clearly
  • 11. Result filtering, sorting & searching • GET /tickets?state=open - query parameter that implements a filter • GET /tickets?sort=-priority - Retrieves a list of tickets in descending order of priority • GET /tickets?q=return&state=open&sort=- priority,created_at - Retrieve the highest priority open tickets mentioning the word 'return'
  • 12. Updates & creation should return a resource representation
  • 14. An API that accepts JSON encoded POST, PUT & PATCH requests should also require the Content-Type header be set to application/json or throw a 415 Unsupported Media Type HTTP status code. JSON encoded POST, PUT & PATCH bodies
  • 16. Rate limiting • X-Rate-Limit-Limit - The number of allowed requests in the current period • X-Rate-Limit-Remaining - The number of remaining requests in the current period • X-Rate-Limit-Reset - The number of seconds left in the current period
  • 18. HTTP status codes • 200 OK - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn't result in a creation. • 201 Created - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource • 204 No Content - Response to a successful request that won't be returning a body (like a DELETE request)
  • 19. • 400 Bad Request - The request is malformed, such as if the body does not parse • 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser • 403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource
  • 20. • 404 Not Found - When a non-existent resource is requested • 405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated user • 429 Too Many Requests - When a request is rejected due to rate limiting
  • 21. THX

Editor's Notes

  1. Важными, но не вбитыми в стену принципами построения АПИ является - следование веб стандартам ( там где это имеет смысл) - простота, интуитивность, целостность - эффективность при соблюдении баланса с другими принципами
  2. Самое замечательное в использовании http методов то, что вам не нужно использовать в своих адресах названия методов или действий которые вы хотите совершать с ресурсом. Все методы говорят сами за то действие которое должно быть описано в соответствующем эндпоинте. Ключевым принципом REST является разделение вашего API на ресурсы и использование http методов в соотвествии с действиями, выполняемыми для этих ресурсов. Ресурсы должны иметь имена существительные, они могут соответствовать моделям в вашей реализации, но это совсем не обязательно. Например в качестве ресурсов могут быть использованы: ticket, user, group
  3. После того как вы определились с ресурсами, вы должны понять какие действия будут совершаться с этими ресурсами и как они будут соотноситься с вашим API. RESTful стратегия определяет использование crud действий в качестве следующих http методов Еще один интересный вопрос использовать ли единственное число, или множественное в обозначении ваших ресурсов. Будьте проще. Простое правило применимо и тут, хотя ваш внутренний грамарнаци возможно скажет что не правильно получать один экземпляр ресурса с использованием множественного числа, но все же что бы сохранить общность лучше всегда использовать множественное число. Это сделает вашу жизнь и жизнь пользователей вашего API значительно проще. К тому же большинство современных фреймворков позволяет удобно реализовать /tickets и /tickets/12 в одном контроллере.
  4. Но как же быть с отношениями ресурсов. Если отношение может существовать только в пределах конкретного ресурса, то и тут REST принципы вполне применимы Если говорить о загрузке отношений вместе с обьектом, то, к примеру, библиотека franctal предлагает такой подход.Они предлагают описывать доступные для дополнения респонс объекты в качестве подключаемых include которые пользователь вашего api может запросить по собственному желанию, в зависимости от того нужны они ему или нет.
  5. Что же насчет действий, который не вписываются в формат CRUD Для этого случая существует несколько подходов.
  6. Поменяйте действие так, что бы оно вписывалось в формат ресурса. Это работает для действий, не принимающих параметра. Например действие активации которое может находится только в двух логических состояниях может быть интерпретировано как PATCH к ресурсу. Относитесь к действию как подресурсу например API гитхаба позволяет добавить и убрать звезду такими запросами Иногда действительно нет другого способа представить действия в виде отношения к ресурсу. Например поиск по нескольким ресурсам. Это ОК, просто сделайте это удобно и убедитесь что реализация хорошо задокументированна
  7. Несколько пунктов о которых не стоит забывать Поскольку вашим приложением пользуются совершенно из разных мест мира не плохо бы шифровать ваш трафик и делать все запросы исключительно по https Документация к вашему апи очень важный аспект написания самого апи, по возможности держите вашу документацию в актуальном состоянии. Своевременно обновляя ее вместе с релизами новых возможностей (или изменений) вашего API. Если вы поддерживаете публичное апи, не забывайте также поддерживать актуальный ченжлог, выписывая туда произошедшие, с API изменения и деприкейтед методы Версионируйте ваше апи, это поможет быстрее разрабатывать новые фичи, а так же поможет не поломать работу со старыми, но измененными функциями. Есть несколько способов версионирования. Используя URL или header Вообще говоря эти подходы можно смешивать, добиваясь более гибкой возможности работы с вашим API и возможности более плавного обновления и перехода к новым версиям для ваших пользователей.
  8. Фильтрация, сортировка, поиск Лучше всего держать ваше API как можно более простым и понятным, однако иногда требуется и получение более сложных, предобработаных результатов. Все эти три пункта могут быть реализованы используя параметры запроса скомпонованные и оформленные разными способами. Один из вариантов как они могут быть оформлены, такой.
  9. Обновление и создание ресурса должны возвращать сам ресурс что бы не требовался повторный запрос данных
  10. Только JSON если кто-то еще интересовался xml, то кажется пришло время оставить его позади
  11. JSON INPUT Если вы следуете тому что рассказано ранее, то наверняка вы используете JSON в качестве output формата. Давайте быть последовательны, будем использовать JSON в качестве input формата. Передача формой может быть уместна когда вы делаете простое API, однако когда на вход должен приходить достаточно большой, комплексный объект, JSON кажется подойдет для этого лучше. Однако тут вынужден признать что я рассматриваю JSON как самый распространенный формат используемый на текущий момент. Конечно существуют альтернативы такие как BSON, MessagePack и другие. Однако я думаю большинство из нас все же пишет веб. А для веба чаще всего удобно иметь человеко-читаемый формат запросов и ответов, однако если для вас критически важна скорость и компактность конечно стоит посмотреть в их сторону.
  12. Немного холивара если в качестве основного клиента вашего API будет JS то кажется имеет смысл использовать стиль принятый в JS а именно кемелкейс, тоже самое можно сказать если основной ваш клиент на каком-то другом языке то стоит использовать договор этого языка CamelCase для C # и Java, snake_case для Python и Ruby. Немного наброса на вентилятор. На основании исследования проведенного в 2010 году снейк кейс на 20% легче для чтения чем кемел кейс. Что значит использования снейк-кейса увеличит читаемость вашего апи. Кроме того многие популярные JSON API уже используют снейк кейс
  13. Рейт лимит Для предотвращения абьюза часто использование апи ( особенно публичных) имеют ограничение на количество запросов. При превышении этого лимита имеет смысл возвращать HTTP status code 429 Too Many Requests Однако очень полезно с каждым запросом возвращать заголовки, с информацией о том, сколько же осталось до прекращения свободного доступа к данным
  14. Ошибки Так же как обычные страницы предоставляют подробные описания ошибки, так и АПИ вполне может быть использовано для подробного пояснения что же собственно пошло не так в обработке запроса. Для описания таких ошибок часто используют такой формат. Вместе с такими ошибками АПИ всегда должно возвращать адекватные коды ответа. Обычно оти коды разделяются на два типа 400е - ошибки обработки данных клиента и 500е - ошибки сервера.