What is REST? “REST service,” “REST API” or “RESTful API” generally means a Web server accepts requests over HTTP and responds in JSON. RESTful almost always means an HTTP-based API. It operates in a request-response fashion over HTTP normally using JSON as the data format in the request and response bodies. ___ REST is an acronym for “REpresentational State Transfer.” Is an architectural style developed by Roy Fielding. Fielding dissertation: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm ). You can read more details about the six constraints here. RESTful means must meet six criteria. The caller (or client): Makes an HTTP request to a URL… Using one of the standard HTTP methods (GET, PUT, POST, PATCH, DELETE, etc.)… With some content (usually JSON) in the body… And waits for a response, which: Indicates status via an HTTP response code And usually has more JSON in the body example call to apple music to get radiohead songs: request: curl -i ‘https://itunes.apple.com/search?term=radiohead&media=music&limit=3’ response: { “resultCount”:3, “results”:[ { “wrapperType”:”track”, “kind”:”song”, “artistId”:657515, “collectionId”:1109714933, “trackId”:1109715066, “artistName”:”Radiohead”, “collectionName”:”In Rainbows”, “trackName”:”15 Step”, “collectionCensoredName”:”In Rainbows”, “trackCensoredName”:”15 Step”, “artistViewUrl”:”https://music.apple.com/us/artist/radiohead/657515?uo=4″, “collectionViewUrl”:”https://music.apple.com/us/album/15-step/1109714933?i=1109715066&uo=4″, “trackViewUrl”:”https://music.apple.com/us/album/15-step/1109714933?i=1109715066&uo=4″, “previewUrl”:”https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview125/v4/af/72/85/af728523-8048-4a8b-9e13-e8f4f64e9d69/mzaf_8205306206851675436.plus.aac.p.m4a”, “artworkUrl30″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/30x30bb.jpg”, “artworkUrl60″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/60x60bb.jpg”, “artworkUrl100″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/100x100bb.jpg”, “collectionPrice”:9.99, “trackPrice”:1.29, “releaseDate”:”2007-10-10T07:00:00Z”, “collectionExplicitness”:”notExplicit”, “trackExplicitness”:”notExplicit”, “discCount”:1, “discNumber”:1, “trackCount”:10, “trackNumber”:1, “trackTimeMillis”:237293, “country”:”USA”, “currency”:”USD”, “primaryGenreName”:”Alternative”, “isStreamable”:true }, { “wrapperType”:”track”, “kind”:”song”, “artistId”:657515, “collectionId”:1109714933, “trackId”:1109715161, “artistName”:”Radiohead”, “collectionName”:”In Rainbows”, “trackName”:”Bodysnatchers”, “collectionCensoredName”:”In Rainbows”, “trackCensoredName”:”Bodysnatchers”, “artistViewUrl”:”https://music.apple.com/us/artist/radiohead/657515?uo=4″, “collectionViewUrl”:”https://music.apple.com/us/album/bodysnatchers/1109714933?i=1109715161&uo=4″, “trackViewUrl”:”https://music.apple.com/us/album/bodysnatchers/1109714933?i=1109715161&uo=4″, “previewUrl”:”https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview115/v4/ba/e4/ac/bae4ac59-3bfa-e4b9-4f4c-03f667324fc0/mzaf_14837742185575446625.plus.aac.p.m4a”, “artworkUrl30″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/30x30bb.jpg”, “artworkUrl60″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/60x60bb.jpg”, “artworkUrl100″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/100x100bb.jpg”, “collectionPrice”:9.99, “trackPrice”:1.29, “releaseDate”:”2007-10-10T07:00:00Z”, “collectionExplicitness”:”notExplicit”, “trackExplicitness”:”notExplicit”, “discCount”:1, “discNumber”:1, “trackCount”:10, “trackNumber”:2, “trackTimeMillis”:242293, “country”:”USA”, “currency”:”USD”, “primaryGenreName”:”Alternative”, “isStreamable”:true }, { “wrapperType”:”track”, “kind”:”song”, “artistId”:657515, “collectionId”:1109714933, “trackId”:1109715168, “artistName”:”Radiohead”, “collectionName”:”In Rainbows”, “trackName”:”Weird Fishes / Arpeggi”, “collectionCensoredName”:”In Rainbows”, “trackCensoredName”:”Weird Fishes / Arpeggi”, “artistViewUrl”:”https://music.apple.com/us/artist/radiohead/657515?uo=4″, “collectionViewUrl”:”https://music.apple.com/us/album/weird-fishes-arpeggi/1109714933?i=1109715168&uo=4″, “trackViewUrl”:”https://music.apple.com/us/album/weird-fishes-arpeggi/1109714933?i=1109715168&uo=4″, “previewUrl”:”https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview115/v4/6c/e9/79/6ce9792e-c06a-b49b-6efe-60b96a690af8/mzaf_5478326228427438939.plus.aac.p.m4a”, “artworkUrl30″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/30x30bb.jpg”, “artworkUrl60″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/60x60bb.jpg”, “artworkUrl100″:”https://is2-ssl.mzstatic.com/image/thumb/Music115/v4/9a/4f/8a/9a4f8a4b-0254-d5ab-74b5-ebe39bbbe85d/634904032463.png/100x100bb.jpg”, “collectionPrice”:9.99, “trackPrice”:1.29, “releaseDate”:”2007-10-10T07:00:00Z”, “collectionExplicitness”:”notExplicit”, “trackExplicitness”:”notExplicit”, “discCount”:1, “discNumber”:1, “trackCount”:10, “trackNumber”:4, “trackTimeMillis”:318187, “country”:”USA”, “currency”:”USD”, “primaryGenreName”:”Alternative”, “isStreamable”:true } ] }
First off, we need to understand what is meant by the term ‘platform’ for the organization. In todays world, the term ‘platform’ is such an overused buzzword that it is largely meaningless. Platforms exist at many levels in the technology stack: hardware, datacenter, database, messaging, etc. and can also be used to describe ecosystems of user experiences. The view presented here is decidedly business focused: the ‘platform’ is really the method of exposing and growing the digital business model and its offerings. So, the following ground rules define the platform as the digital server-side, back-end data and functionality, leaving the user experiences to be crafted (whether mobile, web or other) on top of that business functionality. This API-centric definition of ‘platform’ enables: Rapid user experience revision Consistent user experience across devices Better channel adaptation Faster and cheaper third-party integrations Increased innovation capabilities. Platform Ground Rules Mobile applications are a first-class citizen and consumer of the platform. Making mobile a priority increases ease of use and adoption for everyone. The platform exposes its data and functionality via a complete set of RESTful APIs. An API-based strategy maximizes reuse and flexibility. All service interfaces and events are designed from the ground up to be public facing. Causes design for ease of use, flexibility and reuse. Each team of developers access all APIs using their team’s own registered developer key. Improves security, auditability. There is a single token source and format for all APIs. Assists in ease of use and ensures all functionality is available to consumers. The platform will notify interested observers of all resource state changes via fully-composed events. Enables synchronization asynchronously (for all create, update, delete state changes). All APIs use a single identity to represent the consumer / user. Enables analytics and reasoning about consumers. All APIs have a consistent look and feel, and are documented at a single, publicly-available location. Maximizes reuse and ease of use. No private interfaces. No backdoors. No shared databases across teams (Observe ‘Bounded Contexts’). Ensures the public interfaces are sound. APIs are deployed in a distributed, always-on architecture (multi-node, multi-zone, and multi-region) with a discipline towards resilience. Horizontal scale on commodity hardware, global reach. Account for the inevitable failures.
RESTful Service Best Practices Recommendations for Creating Web Services Todd Fredrich Pearson eCollege @tfredrich www.RestApiTutorial.com Table of Contents Document History 5 Who Should Read This Document 5 Introduction 6 What is REST? 6 Uniform Interface 7 Resource-Based 7 Manipulation of Resources Through Representations 7 Self-descriptive Messages 7 Hypermedia as the Engine of Application State (HATEOAS) 7 Stateless 7 Cacheable 8 Client–server 8 Layered system 8 Code on demand (optional) 8 REST Quick Tips 9 Use HTTP Verbs to Mean Something 9 Sensible Resource Names 9 XML and JSON 9 Create Fine-Grained Resources 10 Consider Connectedness 10 Definitions 10 Idempotence 10 Safety 11 HTTP Verbs 11 GET 11 PUT 12 POST 12 PUT vs POST for Creation 13 DELETE 13 Resource Naming 14 Resource URI Examples 15 Resource Naming Anti-Patterns 16 Pluralization 16 Returning Representations 17 Resource Discoverability Through Links (HATEOAS cont’d) 18 Minimal Linking Recommendations 19 Link Format 19 Wrapped Responses 21 Handling Cross-Domain Issues 22 Supporting CORS 22 Supporting JSONP 22 Querying, Filtering and Pagination 23 Limiting Results 24 Limiting via the Range Header 25 Limiting via Query-String Parameters 25 Range-Based Responses 25 Pagination 26 Filtering and Sorting Results 27 Filtering 27 Sorting 28 Service Versioning 28 Support Versioning via Content Negotiation 29 What version is returned when no version is specified? 31 Unsupported Versions Requested 31 When Should I Create a New Version? 32 Changes that will break contracts 32 Changes considered non-breaking 33 At What Level Should Versioning Occur? 33 Use Content-Location to Enhance Responses 33 Links with Content-Type 33 Finding Out What Versions are Supported 33 How many versions should I support at once? 33 Deprecated 33 How do I inform clients about deprecated resources? 34 Date/Time Handling 34 Date/Time Serialization In Body Content 34 Date/Time Serialization In HTTP Headers 35 Securing Services 35 Authentication 35 Transport Security 36 Authorization 36 Application Security 36 Caching and Scalability 37 The ETag Header 37 HTTP Status Codes (Top 10) 39 Additional Resources 40 Books 40 Websites 40 Document History Date Version Description Feb 10, 2012 Draft Initial draft version. Apr 24, 2012 v1.0 Initial public (non-draft) version. May 29, 2012 v1.1 Minor updates to correct misspellings and clarify wording after feedback from API Best Practices Task force. Aug 2, 2013 v1.2 Updated versioning section. Additional minor corrections of misspellings, wording, etc. Who Should Read This Document This best-practices document is intended for developers who are interested in creating RESTful Web services that provide high reliability and consistency across multiple service suites. By following these guidelines, services are well positioned for rapid widespread public adoption by both internal and external clients. The guidelines in this document are also appropriate for engineers who support services developed using these best practices. While their concerns may be focused on caching practices, proxy rules, monitoring, security, and such, this document may be useful as an overarching service documentation guide of sorts. Additionally, management personnel may benefit from these guidelines by endeavoring to understand the effort required to create services that are publicly consumable that offer high levels of consistency across their service suites. Introduction There are numerous resources on best practices for creating RESTful web services (see the Resources section at the end of this document). Many of the available resources are conflicting, depending on when they were written. Plus, reading and comprehending several books on the subject in order to implement services “tomorrow” is not doable. In order to facilitate quick uptake and understanding of RESTful concepts, without requiring the reading of at least three to five books on the subject, this guide is meant to speed up the process—condensing REST best practices and conventions into just the high points with not a lot of discussion. REST is more a collection of principles than it is a set of standards. Other than its over-arching six constraints, nothing is dictated. There are “best practices” and de-facto standards but those are constantly evolving—with religious battles waging continuously. Designed to be brief, this document provides recommendations and some cookbook-style discussion on many of the common questions around REST and provides some short background information to offer support for effective creation of real-world, production-ready, consistent RESTful services. This document aggregates information available in other sources, adapting it with experience gained through hard knocks. There is still considerable debate as to whether REST is better than SOAP (and vice versa), and perhaps there are still reasons to create SOAP services. While touching on SOAP, this document won’t spend a lot of time discussing relative merits. Instead, because technology and the industry marches on, we will proceed with the assumption that leveraging REST is the current best practice for Web service creation. The first section offers an overview of what REST is, its constraints, and what makes it unique. The second section supplies some quick tips as little reminders of REST service concepts. Later sections go more in depth to provide the Web service creator more support and discusses the nitty-gritty details of creating high-quality REST services capable of being publicly exposed in a production environment. What is REST? The REST architectural style describes six constraints which were originally communicated by Roy Fielding in his doctoral dissertation (see http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm). They define the basis of RESTful-style. The six constraints are: Uniform Interface Stateless Cacheable Client-Server Layered System Code on Demand A more detailed discussion of the constraints follows: Uniform Interface The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the application architecture, which enables each part to evolve independently. The four guiding principles of the uniform interface are: Resource-Based Individual resources are identified in requests using URIs as resource identifiers. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server does not send its database, but rather, some HTML, XML, or JSON that represents some database records expressed, for instance, in Finnish and encoded in UTF-8, depending on the details of the request and the server implementation. Manipulation of Resources Through Representations When
Do only one thing and do it well. The “one thing” is defined by a “Bounded Context” in Domain-Driven Design (DDD). Own your own data. No shared data stores. Embrace eventual consistency. Don’t read your writes. Publish your own state-changes (minimally) to an event log. Leverage event logging and/or streaming to replicate and denormalize data from other services. The event log must be subscribable to publish events to subscribers. The event log must be durable and must not lose messages for publishing and replay. Examples: Kafka, Confluent.io, Amazon Kinesis. When aggregating microservice calls, use asynchronous, non-blocking I/O. Perform as much as possible asynchronously. Support a registry/discovery mechanism. Examples: Consul, Eureka Support Location Transparency. Support statelessness–no sticky sessions. Support the use of back-pressure (see, Reactive Streams specification) to avoid cascading failures. Examples: RxJava Support the Circuit Breaker pattern to manage faulty service dependencies. Examples: Hystrix, Apache Zest Consider CQRS to scale reads separately from writes.
Multiple, identical requests gives same results as a single request. E.g. RESTful service calls GET, PUT, DELETE, HEAD, OPTIONS, TRACE. From a RESTful service standpoint, for an operation (or service call) to be idempotent, clients can make that same call repeatedly while producing the same result. In other words, making multiple identical requests has the same effect as making a single request. Note that while idempotent operations produce the same result on the server (no side effects), the response itself may not be the same (e.g. a resource’s state may change between requests). The PUT and DELETE methods are defined to be idempotent. However, there is a caveat on DELETE. The problem with DELETE, which if successful would normally return a 200 (OK) or 204 (No Content), will often return a 404 (Not Found) on subsequent calls, unless the service is configured to “mark” resources for deletion without actually deleting them. However, when the service actually deletes the resource, the next call will not find the resource to delete it and return a 404. However, the state on the server is the same after each DELETE call, but the response is different. GET, HEAD, OPTIONS and TRACE methods are defined as safe, meaning they are only intended for retrieving data. This makes them idempotent as well since multiple, identical requests will behave the same. Source: https://restapitutorial.com/