Presentation is loading. Please wait.

Presentation is loading. Please wait.

REST API Design Borrowed heavily from:

Similar presentations


Presentation on theme: "REST API Design Borrowed heavily from:"— Presentation transcript:

1 REST API Design Borrowed heavily from:

2 API API = Application Programming Interface
APIs expose functionality of an application or service that exists independently of the API. A well-designed API makes programming easier by abstracting the underlying implementation and only exposing objects or actions the developer needs. Examples (web): Facebook Twitter Google POSIX, Microsoft Windows API, the C++ Standard Template Library, and Java APIs are examples of different forms of APIs. Example: API design in the small. Image there wasn’t a method for displaying Toast messages. Writing such a method is an example of API design. General rules-of-thumb for API design:

3 REST REST stands for Representational State Transfer
REST is an architectural style for networked hypermedia applications REST is used to build Web services that are lightweight, maintainable, and scalable. REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol. RESTful services should have following properties and features: Representations (example: JSON, XML) Messages (HTTP Request) URIs Uniform interface Stateless Links between resources URI = identification. URL = location. A URL is a URI. In a REST web service, requests made to a resource's URI will elicit a response that may be in XML, HTML, JSON or some other defined format. The response may confirm that some alteration has been made to the stored resource, and it may provide hypertext links to other related resources or collections of resources. Using HTTP, as is most common, the kind of operations available include those predefined by the HTTP verbs GET, POST, PUT, DELETE and so on. By making use of a stateless protocol and standard operations REST systems aim for fast performance, reliability, and the ability to grow, by using reused components that can be managed and updated without affecting the system as a whole, even while it is running. REST design =  a network of web resources (a virtual state-machine) where the user progresses through the application by selecting links, such as /user/tom, and operations such as GET or DELETE (state transitions), resulting in the next resource (representing the next state of the application) being transferred to the user for their use.

4 RESTful Design Components
There are three distinct components involved in RESTful API design: the application the API code the client. The application for which an API is to be provided exists independently of that API. Like any application, the application for which the API is to be created contains state. That state is dynamic, and will change due to various operations that are executed on it. The job of the API code is to access the application state, as well as the operations on that state, via the application interface, and expose it as a RESTful API. The result of this transformation would be RESTful resources, operations on those resources, and relationships between the resources. All of these are described by what we call the RESTful resource model. Resources are the foundation behind any RESTful API. Relationships between resources are expressed as hyperlinks in the representation of the resource. This is one of the fundamental principles of RESTful API design. Resources also respond to a very limited set of operations (usually just 4), which is a second principle of the RESTful architectural style. The client consumes the RESTful API via the standard HTTP protocol.

5 Resources The fundamental concept in any RESTful API is the resource.
Resources model objects from the application data model. These resources can be pictures, video files, Web pages, business information, etc. A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. Each resource has a unique URL REST Resource is similar to an object in OOP. Resources have limited number of operations: GET, POST, PUT and DELETE methods.

6 Addressing Resources A RESTful service uses a directory hierarchy like human readable URIs to address its resources. The job of a URI is to identify a resource or a collection of resources. The actual operation is determined by an HTTP verb. The URI should not say anything about the operation or action. This enables us to call the same URI with different HTTP verbs to perform different operations. Bad: Example resource:

7 Collections Resources can be grouped into collections.
Each collection is homogeneous so that it contains only one type of resource. Collections are unordered. Collections are themselves resources as well. Example collection:

8 Resource Model of an API
The resource model of an API consists: Available resources types Their behavior Their relationships The resource model can be viewed as the RESTful mapping of the application data model.

9 Resource Data Resources have data associated with them.
In JSON, just three types of data exist: scalar (number, string, boolean, null). array object Data associated with a resource is modeled as key:value pairs on the JSON object.

10 JSON Object Example

11 REST Metadata In addition to exposing application data, resources also include other information that is specific to the RESTful API. Such information includes URLs and relationships. Example: { "href" : " "username" : "jlpicard", " " : "directory" : { "href" : " }, … }

12 Entry Point A RESTful API needs to have one and exactly one entry point. The URL of the entry point needs to be communicated to API clients so that they can find the API. It is common for the entry point to contain some or all of the following information: Information on API version, supported features, etc. A list of top-level collections. A list of singleton resources Each collection and resource in the API has its own URL. URLs should never be constructed by an API client. Instead, the client should only follow links that are generated by the API itself.

13 Messages The client and service talk to each other via messages.
Clients send a request to the server, and the server replies with a response. Apart from the actual data, these messages also contain some metadata about the message. HTTP Request: Verb = GET, PUT, POST, DELETE, etc URI = the URI of the resource on which the operation is going to be performed Request Header = metadata as a collection of key-value pairs of headers and their values. These settings contain information about the message and its sender like client type, the formats client supports, format type of the message body, cache settings for the response, etc. Request Body = the actual message content.

14 Request Message Example
POST Host: MyService.com Content-Type: text/xml; charset=utf-8 Content-Length: 123 <?xml version="1.0" encoding="utf-8"?> <Person> <Name>Larry</Name> <Country>US</Country> </Person> Could be JSON object.

15 Response Message Example
HTTP/ OK Date: Sat, 23 Aug :31:04 GMT Server: Apache/2 Last-Modified: Wed, 01 Sep :24:52 GMT Accept-Ranges: bytes Content-Length: Cache-Control: max-age=21600, must-revalidate Expires: Sun, 24 Aug :31:04 GMT Content-Type: text/html; charset=iso <html> <head><title>CS449 Calendar</title></head> <body> ... Could be JSON object.

16 Methods Methods are verbs or actions that can be performed on resources Methods can be executed on resources via their URL. Standard methods that have a well-defined meaning for all resources and collections: Method Scope Semantics Quality GET Collection Retrieve all resources in a collection Safe Resource Retrieve a single resource POST Create a new resource in a collection N/A PUT Update a resource Idempotent DELETE Delete a resource HEAD Retrieve only the response headers OPTIONS List the allowed operations on a resource. HEAD can be used to quickly check whether a resource exists on the server or not. There are two ways to find out which methods are accepted by a resource or collection. Use the OPTIONS method on the URL, and look at the “Allow” header that is returned. This header contains a comma-separated list of methods are are supported for the resource or collection. Just issue the method you want to issue, but be prepared for a “405 Method Not Allowed” response that indicates the method is not accepted for this resource or collection. The HTTP RFC specifies that PUT must take a full new resource representation as the request entity. An additional method called PATCH has been proposed recently. The semantics of this call are like PUT in that it updates a resource, but unlike PUT, it applies a delta rather than replacing the entire resource.

17 Methods [cont.] GET is Safe. A Safe operation is an operation that does not have any effect on the original value of the resource. PUT and DELETE are Idempotent. An Idempotent operation is an operation that gives the same result no matter how many times you perform it. Note, if you are adding a resource with PUT you have to specify the unique ID of the resource. Classifying methods as Safe and Idempotent makes it easy to predict the results in the unreliable environment of the Web where the client may fire the same request again.

18 Difference between PUT and POST
PUT is idempotent while POST is not. No matter how many times you send a PUT request, the results will be same. POST is not an idempotent method. Making a POST multiple times may result in multiple resources getting created on the server. With PUT, it is the client's job to choose a unique name or ID for the resource. With POST, the server decides. This is why POST is not idempotent. There is no difference between PUT and POST if the resource already exists (assuming POST is sending ID of resource which is not generally recognized as a good practice)

19 Options The method OPTIONS is used to get a list of allowed operations on the resource. For example Request: OPTIONS HTTP/1.1 HOST: api.business.com Response: 200 OK Allow: HEAD, GET, PUT

20 Relationships Resources do not exist in isolation, but have relationships to other resources. A resource representation can contain links to other resources. The representations returned by the service should drive the process flow as in case of a website. When you visit any website, you are presented with an index page. You click one of the links and move to another page and so on. Relationships are defined via link object or href attribute. Relationships are between RESTful resources and may or may not be between mapped objects in application data model.

21 Stateless A RESTful service is stateless and does not maintain the application state for any client. A request cannot be dependent on a past request and a service treats each request independently. HTTP is a stateless protocol by design and you need to do something extra to implement a stateful service using HTTP. Example stateful design (not RESTful): Request1: GET HTTP/1.1 Request2: GET HTTP/1.1 Design your service in a way that a request never refers to a previous request. Stateless services are easier to host, easy to maintain, and more scalable.

22 HATEOAS HATEOAS = Hypermedia as the Engine of Application State
HATEOAS is a constraint of the REST application architecture that distinguishes it from most other network application architectures. HATEOAS is how the web works. Ever notice how the websites amazon.com, google.com, twitter.com etc. don’t come with an instruction manual for using them? You don’t need one. You simply discover the features of a website by following hyperlinks. Nice feature of the web because otherwise every time there was a change to the structure of a website the website user guide would have to be updated, redistributed and reread. Websites are freer to evolve because they are built on the concept of HATEOAS. Wouldn’t it be nice if a web service API were designed in the same way? “Not ready for HATEOAS yet”:

23 HATEOAS API A REST client enters a REST application through a simple fixed URL. All future actions the client may take are discovered within resource representations returned from the server. The client transitions through application states by selecting from the links within a representation or by manipulating the representation in other ways afforded by its media type. In this way, RESTful interaction is driven by hypermedia, rather than out-of-band information (written documentation) The media types used for these representations, and the link relations they may contain, are standardized.

24 Example Non-HATEOAS Response: { "name": "Alice", } HATEOAS Response:
"links": [ { "rel": "self", "href": " } ] rel = relationship


Download ppt "REST API Design Borrowed heavily from:"

Similar presentations


Ads by Google