CS计算机代考程序代写 scheme javascript database chain Java case study cache algorithm SE457 Week 5 – REST (Continued)

SE457 Week 5 – REST (Continued)
Steven Engelhardt
DePaul University
Spring 2021
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 1 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 2 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 3 / 75

Last Week
• REST is the most common style of web service today, particularly over the public Internet.
• REST APIs are all about resources and representations
• REST deeply embraces the HTTP protocol for managing resources
• The most common data transfer format for REST APIs is JavaScript Object Notation, or JSON
• JAX-RS is the “official” Java framework for creating REST APIs
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 4 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 5 / 75

Question 1
Q Explain the impact of using a development tool to auto-generate contracts on standardization.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 6 / 75

Question 1
Q Explain the impact of using a development tool to auto-generate contracts on standardization.
A There is only as much standardization in the output of the generation as there is in the design of the underlying implementation. Since there is often very little consistency in the source API, it stands to reason that the generated contracts would exhibit very little standardization. Or at least not as much standardization as we could get by hand-writing that contract.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 6 / 75

Question 2
Q We may not always be able to have every property for every service, especially early on. How do we decide which properties to emphasize and which to de-emphasize?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 7 / 75

Question 2
Q We may not always be able to have every property for every service, especially early on. How do we decide which properties to emphasize and which to de-emphasize?
A It all comes down to the organization’s pain points and goals. If you have an extremely heterogeneous environment, then you might choose to emphasize standardization over discoverability, for example. That’s because standardization is the only way you’re going to be able to hide the underlying platforms. If you happen to have very few support personnel, then you might choose to emphasize autonomy. If you’re drowning in duplicated code, then redundancy might be your focus of choice. Keep in mind that most of these are not boolean – each property is almost always present in some degree. The trick is figuring out how to nurture the properties that you feel will get your organization the greatest advantage.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 7 / 75

Question 3
Q What are some practical considerations if our goal is to achieve complete autonomy, meaning that no two services share any of the same resource?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 8 / 75

Question 3
Q What are some practical considerations if our goal is to achieve complete autonomy, meaning that no two services share any of the same resource?
A The biggest thing to consider is expense. There are very real costs associated with this kind of autonomy not the least of which is things like licensing costs. You can get around some of the hosting environment issues using things like virtual machines although you’re technically still sharing hardware resources at that point.
Performance may be another issue. If there is no shared database, then you are virtually guaranteed some kind of service call across a network boundary to retrieve data not in your database. That can get expensive.
There are other, similar costs for things like maintenance (patches, deployments, etc.). You get the idea.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 8 / 75

Question 4
Q All of the other principles are arguably considered good practice because of their impact on composability. What are the major benefits of service composition?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 9 / 75

Question 4
Q All of the other principles are arguably considered good practice because of their impact on composability. What are the major benefits of service composition?
A Service composition is really where we start to see reuse come into play. Having the ability to de-construct a process and then re-construct it from other, better designed parts is extremely powerful. Even more powerful is the idea that we can continue to use the existing parts in an almost limitless set of new compositions.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 9 / 75

Question 5
Q Consider response time and scalability. For each of those non-functional requirements select the service property that you think most impacts it and explain why.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 10 / 75

Question 5
Q Consider response time and scalability. For each of those non-functional requirements select the service property that you think most impacts it and explain why.
A For response time standardization is one way to improve it because it will result in less overhead from translations. Autonomy is another one because a highly autonomous service will require fewer outside resources, which may also improve response time. For scalability statelessness is the obvious way to improve it.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 10 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 11 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 12 / 75

Spring Greeting Service
• Let’s refresh our memory of what REST services look like by looking at Spring’s greeting service from its Building a RESTful Web Service guide
• See https://spring.io/guides/gs/rest-service/ for the guide
• See https://github.com/spring-guides/gs-rest-service.git
for the source code (Spring framework specific)
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 13 / 75

Compiling and Starting Service
$ git clone https://github.com/spring-guides/gs-rest-service.git
$ cd gs-rest-service/complete
$ mvn spring-boot:run

. ____ _ ____ /\\/___’_____(_)___ ___\\\\ ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \ \
\\/ ___)||_)|||||||(_|| )))) ‘ |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.2.RELEASE)

2020-05-10 19:34:22.248 INFO 32364 — [
embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (
http) with context path ”
2020-05-10 19:34:22.252 INFO 32364 — [ main] c.e.
restservice.RestServiceApplication : Started
RestServiceApplication in 1.643 seconds (JVM running for 1.936)
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 14 / 75
main] o.s.b.w.

Simple Request/Repsonse
$ curl -v http://localhost:8080/greeting
GET /greeting HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.64.1
Accept: */*
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 11 May 2020 00:32:33 GMT
{“id”:1,”content”:”Hello, World!”}
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 15 / 75

Request/Repsonse With Parameter
$ curl -v “http://localhost:8080/greeting?name=Steve”
GET /greeting?name=Steve HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.64.1
Accept: */*
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 11 May 2020 00:33:02 GMT
{“id”:2,”content”:”Hello, Steve!”}
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 16 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 17 / 75

REST Design Methodology
1 Identify resources to be exposed as services (e.g., yearly risk report, book catalog, purchase order, open bugs, polls and votes)
2 Model relationships (e.g., containment, reference, state transitions) between resources with hyperlinks that can be followed to get more details (or perform state transitions)
3 Define “nice” URIs to address the resources
4 Understand what it means to do a GET, POST, PUT, DELETE for
each resource (and whether it is allowed or not)
5 Design and document resource representations
6 Implement and deploy on Web server
7 Test with a Web browser
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 18 / 75

REST URI Design Guidelines
• Prefer Nouns to Verbs
• Keep your URIs short
• Use plurals for collections (/accounts not /account)
• If possible follow a “positional” parameter-passing scheme for algorithmic resource query strings (instead of the key=value&p=v encoding)
• Some use URI postfixes to specify the content type (e.g. a URL ending in .html). This may break the abstraction.
• Do not change URIs
• Use redirection if you really
need to change them • Make URI routing as a
first-class citizen largely independent from request fulfillment
• Don’t force yourself into a single tree hierarchy
• It can be OK to have multiple URIs point to the same resource, but consider using redirection to point clients to the canonical URI
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 19 / 75

Collections in REST
• Users of GET on collection endpoints are typically trying to show a table or chart of many items
• They typically would like to retrieve only the data necessary for them to render, and in a minimum number of round-trips (preferably one)
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 20 / 75

Collections in REST
• Sorting
• GET /companies?sort=state,-marketValue
• Filtering
• GET /companies?category=banking
• GET /companies?numEmployees>=1000
• Pagination
• GET /companies?skip=50&limit=25 or • GET /companies?page=3&pagesize=25
• Field selection
• GET /companies?fields=state,marketValue
• Searching
• GET /companies?q=Digital%20McKinsey
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 21 / 75

Collections in REST
• HowtogetatotalcountofallrecordssoIcandisplayapagexofy UI?
• How to get a list of all fields for field selection?
• How to discover which fields are sortable? Filterable?
• How to represent complicated Boolean filters (e.g. parentheses, and, or, string starts with, string contains, etc.)
• GET querystring length limits (2K-4K characters)
• How to represent fields on related items (e.g. for the top 10 largest companies by market value, show me their name, their state of incorporation, and the state of incorporation’s population)
• How does above design affect cacheability?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 22 / 75

Encryption
• Encryption of data-in-transit prevents eavesdropping and replay attacks
• To support encryption of data-in-transit, use TLS and provide a HTTPS endpoint in addition to the typical HTTP endpoint
• If your API deals with sensitive data or needs to protect authentication credentials in transit, provide only a HTTPS endpoint.
• Beware: HTTPS can make debugging more challenging, as it is more difficult to capture requests and responses
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 23 / 75

Authentication
• Authentication is the process of establishing identity, i.e. who is making the requests to your service
• For services, the caller identity is frequently an application rather than a human.
• Establishing identity is necessary to implement data security, data isolation, throttling, etc.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 24 / 75

Authentication: How to Authenticate
Common methods of RESTful service authentication include:
• HTTP authentication (basic, digest)
• API keys
• HTTP bearer authentication (e.g. OAuth 2.0, OpenID Connect Discovery)
• JSON Web Tokens
• TLS mutual authentication
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 25 / 75

Authentication: HTTP Basic Authentication
• HTTP basic authentication is the oldest form of authentication available over HTTP.
• It consists of passing a HTTP header in the form Authorization: Basic , where credentials is the Base64 encoding of ID and password joined by a single colon :
• Example:
GET /greeting HTTP/1.1
Host: localhost:8080
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
• HTTP basic authentication should only be used over an encrypted channel (e.g. HTTPS) and is relatively uncommon for RESTful APIs
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 26 / 75

Authentication: API Keys
• An API key is a token that a client provides when making API calls. It is a shared secret between a client and a server.
• API keys can be passed in the query string:
GET /greeting?api_key=abcdef12345 HTTP/1.1
• …or as a request header:
GET /greeting HTTP/1.1
X-API-Key: abcdef12345
• Like Basic authentication, API key-based authentication is only considered secure if used together with other security mechanisms such as HTTPS/SSL.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 27 / 75

Authentication: Bearer Tokens
• Bearer authentication involves security tokens called bearer tokens. The name “Bearer authentication” can be understood as “give access to the bearer of this token.” It originated as part of OAuth 2.0.
• A bearer token is a cryptic string, usually generated by the server in response to a login request.
• The client must send this token in the Authorization header when making requests to protected resources:
GET /greeting HTTP/1.1
Authorization: Bearer
• Unlike API key authentication, a bearer token typically has a limited lifetime (e.g. a few hours)
• Like Basic authentication, bearer token-based authentication is only considered secure if used together with other security mechanisms such as HTTPS/SSL.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 28 / 75

Authentication: JSON Web Tokens
• A JSON Web Token is a JSON payload which asserts a number of claims (e.g. “The caller has logged in as admin”) and is frequently digitally signed
• JSON Web Tokens serve a similar purpose with SAML assertions
• The encoded token is frequently passed as a bearer token in the Authorization HTTP header
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 29 / 75

Authentication: TLS Mutual Authentication
• The TLS protocol (i.e. that behind https://) supports the notion of mutual or two-way authentication
• Using this technology, a client authenticates to a server using a X.509 certificate when a TLS connection is established
• Mutual TLS authentication is much more widespread in business-to-business (B2B) applications, where a limited number of programmatic and homogeneous clients are connecting to specific web services, the operational burden is limited, and security requirements are usually much higher as compared to consumer environments.1
1Wikipedia contributors. Mutual authentication — Wikipedia, The Free Encyclopedia. [Online; accessed 10-May-2020]. 2020. url: https://en.wikipedia.org/wiki/Mutual_authentication.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 30 / 75

Authentication: Tips and Tricks
• Consider adopting an off-the-shelf authentication strategy like OpenID Connect Discovery
• Beware of authentication credentials showing in logs, particularly if your authentication tokens are passed in the query string
• Don’t forget that you may need to rotate your secrets regularly
• A frequent design issue is one of delegated trust. If I connect to my bank website and issue a transaction, which calls a service, which calls another service, which calls another service, how does the last service in the chain know (in a secure manner) that the transaction was authorized by me, or is on my behalf?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 31 / 75

Safety and Idempotency
• In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides 2 returning a value (the main effect) to the invoker of the operation.
In the presence of side effects, a program’s behaviour may depend on history; that is, the order of evaluation matters.
• A safe (or nullipotent) method is one where calling it produces no side effects: retrieving or accessing a record does not change it.
• An idempotent method is one where the state of the system exposed by the API is unchanged no matter how many times more than once the same request is repeated.
2Wikipedia contributors. Side effect (computer science) — Wikipedia, The Free Encyclopedia. [Online; accessed 10-May-2020]. 2020. url: https://en.wikipedia.org/wiki/Side_effect_(computer_science).
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 32 / 75

Safety and Idempotency: HTTP Requirements
The HTTP protocol requires us to implement the following levels of safety for each of the following HTTP verbs:
Method Safety
GET Safe
POST Unsafe
PUT Idempotent DELETE Idempotent PATCH Unsafe OPTIONS Safe
HEAD Safe
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 33 / 75

Safety and Idempotency: What Not To Do
GET /employees/123?action=delete
HTTP/1.1
Host: api.example.com
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 34 / 75

Caching in REST APIs
• Caching is the ability to store copies of frequently accessed data in several places along the request-response path.
• When a consumer requests a resource representation, the request goes through a cache or a series of caches (local cache, proxy cache, or reverse proxy) toward the service hosting the resource. If any of the caches along the request path has a fresh copy of the requested representation, it uses that copy to satisfy the request. If none of the caches can satisfy the request, the request travels all the way to the service (or origin server as it is formally known).3
• Optimizing the network using caching improves the overall quality-of-service in the following ways:
• Reduce bandwidth
• Reduce latency
• Reduce load on servers • Hide network failures
• Cacheability is one of the architectural concerns of HTTP, and thus REST.
3restfulapi.net. Caching REST API Response. [Online; accessed 10-May-2020]. 2020. url: https://restfulapi.net/caching/.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 35 / 75

Caching: Communicating Cacheability
• RESTful APIs communicate the cacheability of their responses via various HTTP cache headers in their response
• GET requests, since they are safe, are frequently cachable.
• Other verbs can be made cacheable by the server by providing the
appropriate cache headers.
• See https://www.mnot.net/cache_docs/ for a useful walkthrough of HTTP caching.
• There are many cache headers, and we will go through some of them now.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 36 / 75

Caching: Expires Header
• The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server.
HTTP/1.1 200 OK
Expires: Fri, 20 May 2016 19:20:49 IST
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 37 / 75

Caching: Cache-Control Header
• The Cache-Control header can communicate many different caching policies. Here are some examples.
• max-age=seconds — specifies the maximum amount of time that a representation will be considered fresh. seconds is the number of seconds from the time of the request you wish the representation to be fresh for.
• public — marks authenticated responses as cacheable; normally, if HTTP authentication is required, responses are automatically private.
• private — allows caches that are specific to one user (e.g., in a browser) to store the response; shared caches (e.g., in a proxy) may not.
• no-cache — forces caches to submit the request to the origin server for validation before releasing a cached copy, every time. This is useful to assure that authentication is respected (in combination with public), or to maintain rigid freshness, without sacrificing all of the benefits of caching.
• no-store — instructs caches not to keep a copy of the representation under any conditions.
• must-revalidate — tells caches that they must obey any freshness information you give them about a representation. HTTP allows caches to serve stale representations under special conditions; by specifying this header, you’re telling the cache that you want it to strictly follow your rules.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 38 / 75

Caching: Cache-Control Example
Cache-Control: public, max-age=3600, must-revalidate
Interpretation: The client or an intermediate proxy may cache the response for up to 1 hour, but must strictly follow these rules and may never serve a stale representation. All responses are cacheable, even authenticated ones.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 39 / 75

Caching: Validators
• If a representation is stale (i.e. the cache has expired), the client can ask the origin server to validate it, or tell the cache whether the copy that it has is still good.
• The most common validator is the time that the document last changed, as communicated in Last-Modified header. When a cache has a representation stored that includes a Last-Modified header, it can use it to ask the server if the representation has changed since the last time it was seen, with an If-Modified-Since request.
GET /resource HTTP/1.1
If-Modified-Since: Tue, 20 Oct 2015 07:28:20 GMT
HTTP/1.1 304 Not Modified
• An alternative technique is an ETag, which are unique identifiers generated by the server and changed every time the representation does.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 40 / 75

Content Negotiation
• HTTP allows a resource at a given URI to have multiple representations.
• Content negotiation is the mechanism that is used for a user agent to specify which representation is best suited for the user.
• Some common ways REST API authors use content negotation: • To allow a single API to work in JSON or XML, depending on the
client’s preference
• To implement one form of API versioning
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 41 / 75

Content Negotiation: Preferred Representation Example
GET /users/42 HTTP/1.1
Accept: application/json,
application/xml;q=0.9,*/*;q
=0.8
HTTP/1.1 200 OK
Content-Type: application/json
{
“firstName”: “Joe”,
“lastName”: “Bloggs”
}
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 42 / 75
GET /users/42 HTTP/1.1
Accept: application/xml,
application/json;q=0.9,*/*;q
=0.8
HTTP/1.1 200 OK
Content-Type: application/xml

Joe
Bloggs

Content Negotiation: Versioning Example
GET /users/42 HTTP/1.1
Accept: application/vnd.linn.user+
json; version=1
HTTP/1.1 200 OK
Content-Type: application/vnd.linn
.user+json; version=1
{
“firstName”: “Joe”,
“lastName”: “Bloggs”
}
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 43 / 75
GET /users/42 HTTP/1.1
Accept: application/vnd.linn.user+
json; version=2
HTTP/1.1 200 OK
Content-Type: application/vnd.linn
.user+json; version=2
{
“name”: {
“first” : “Joe”,
“last”: “Bloggs”
}
}

Versioning
• All APIs evolve over time. Occassionally breaking backwards compatibility is necessary in order to produce a far better product.
• You should design a versioning strategy into your REST API up front to make the path towards upgrading as straightforward as it can be.
• We’ve already seen the content negotiation-based versioning strategy. Here are a few others.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 44 / 75

Versioning: Version in URL Path
GET /v1/clients HTTP/1.1
Host: api.example.com
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 45 / 75

Versioning: Version in Query String
GET /clients?version=1.0 HTTP/1.1
Host: api.example.com
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 46 / 75

Versioning: Version in Custom HTTP Header
GET /clients HTTP/1.1
Host: api.example.com
Accept-Version: 1.0
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 47 / 75

API Localization
• If your API will be used globally, you may need to design localization into it.
• Common areas of localization include language, currency, dates/times, and number formatting.
• Let’s look at a few of these areas now.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 48 / 75

API Localization: Language
• There are a number of ways that REST APIs can support multiple languages. Here are a few examples.
• In the URL path:
• In the URL query string:
• As part of HTTP language negotiation:
GET /en-US/clients HTTP/1.1
Host: api.example.com
GET /clients?locale=en HTTP/1.1
Host: api.example.com
GET /clients HTTP/1.1
Accept-Language: fr; q=1.0, en; q=0.5
Host: api.example.com
• Prefer HTTP language tags (see RFC2616 section 3.10)
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 49 / 75

API Localization: Date and Times
• Dates and times are deceivingly complex.
• Most REST APIs use ISO 8601-based locale-invariant representations for date and times, and require the API client to format it in the appropriate way for the user.
• Example ISO 8601 dates and times: • 2020-05-10
• 2020-05-10T10:34:42-05:00 • 2020-05-11T03:34:42+00:00 • 2020-05-11T03:34:42Z
• 2020-W20
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 50 / 75

Cross-Origin Resource Sharing (CORS)
• Your API may be located on a different host (origin) from your website.
• By default, web browsers will not allow cross-origin requests, so browsers may not be able to call your API directly. This is intended as a security precaution against malicious websites which might try to make authenticated malicious AJAX calls to your API.
• You can use cross-origin resource sharing (CORS) to communicate to the browser when it is OK for clients to make requests directly to it.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 51 / 75

CORS: Example
CORS Request
OPTIONS /resource/12345
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit
/536.30.1 (KHTML, like …
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: origin, x-requested-with, accept
Origin: http://foo.client.com
CORS Response
HTTP/1.1 200 OK
Date: Wed, 20 Nov 2013 19:36:00 GMT
Server: Apache-Coyote/1.1
Content-Length: 0
Connection: keep-alive
Access-Control-Allow-Origin: http://foo.client.com
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 52 / 75

HATEOAS
• HATEOAS means Hypermedia as the Engine of Application State.
• The REST architectural style lets you use hypermedia links in the response contents so that the client can dynamically navigate to the appropriate resource by traversing the hypermedia links.
• Example:
GET /customers HTTP/1.1
Host: localhost:8080
HTTP/1.1 200 OK
[{
“name”: “Alice”,
“links”: [ {
“rel”: “self”,
“href”: http://localhost:8080/customer/1
}] }]
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 53 / 75

Asynchronous Operations
• Problem: How to represent a long-lived, asynchronous operation as a REST request?
• Answer: Treat the job as the resource
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 54 / 75

Asynchronous Operations: Submit Job
Request
POST /blogs HTTP/1.1
Content-type: application/vnd.myblog.article+xml ; version=1.1
Response
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 55 / 75

My blogpost
John Doe
This is the content for my blog article

HTTP/1.1 202 Accepted
Location: /queue/621252

Asynchronous Operations: In Queue
Request
GET /queue/621252 HTTP/1.1
Response
HTTP/1.1 200 OK

Pending
10 minutes

Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 56 / 75

Asynchronous Operations: In Progress
Request
GET /queue/621252 HTTP/1.1
Response
HTTP/1.1 200 OK

In progress
3 minutes, 25 seconds

Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 57 / 75

Asynchronous Operations: Job Completed
Request
GET /queue/621252 HTTP/1.1
Response
HTTP/1.1 303 See Other
Location: /blog/20010101-myblogarticle
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 58 / 75

Asynchronous Operations: Create Job Sequence Diagram
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 59 / 75

Asynchronous Operations: Checking Job Status
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 60 / 75

Asynchronous Operations: Cancelling Job
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 61 / 75

Asynchronous Operations: Additional Thoughts
• Above system is not idempotent. What happens if the processor fails after creating a record in the blog database but before acknowledging the message?
• Cancellation requires message queue to support message cancellation (not all do!)
• Potential race condition between cancellation and job processing
• Which system calculates job ETA, and how?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 62 / 75

Documenting a RESTful Service
• Commonly-used tools include OpenAPI Spec, Swagger, Spring REST Docs, RAML, others
• Consider that your service may need more than just API reference documentation. It might need:
• Context
• Tutorials
• Sample code
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 63 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 64 / 75

GitHub REST API v3
• GitHub is a web-based hosting service for version control using git
• The GitHub REST API allows full programmatic access to GitHub resources, including:
• Organizations • Users
• Repositories • Pull requests • Issues
• Gists • Etc.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 65 / 75

GitHub REST API Example
GET /users/sengelha HTTP/1.1 Host: api.github.com
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8 Cache-Control: public, max-age=60, s-maxage=60 Vary: Accept
ETag: W/”2a42944dfddb4872644a3be056d690f7″ Last-Modified: Thu, 09 Apr 2015 19:42:52 GMT Access-Control-Allow-Origin: *
Content-Length: 1218
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 48
X-RateLimit-Reset: 1525799546
{
“login”: “sengelha”,
“id”: 482551,
“avatar_url”: “https://avatars0.githubusercontent.com/u/482551?v=4”, …
}
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 66 / 75

GitHub REST API Documentation
• https://developer.github.com/v3/
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 67 / 75

GitHub REST API Design Decisions
• All access via HTTPS
• All data sent and received via JSON with github-specific
content-types
• Authentication supports HTTP basic, OAuth2 token (either as header or query-string parameter), and OAuth2 key/secret
• Some endpoints are unauthenticated (e.g. GET /users/xxx), some require authentication
• Versioning via content-negotiation (Accept: application/vnd.github.v3+json)
• All timestamps in ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ), which also supports time zone specifications
• No locale support
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 68 / 75

GitHub REST API Design Decisions
• Fetching a list of resources returns summary descriptions. Fetching an individual resource returns a detailed representation.
• Many API methods take optional parameters, frequently used to filter collections (e.g. https://api.github.com/repos/vmg/ redcarpet/issues?state=closed)
• Requests that return multiple items will be paginated to 30 items by default, but this can be controlled with a ?per_page parameter (up to a maximum of 100)
• Multiple URL paths to collection of same noun (e.g. GET /user/repos, GET /users/:username/repos, GET /orgs/:org/repos)
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 69 / 75

GitHub REST API Design Decisions
• Requests are rate limited to 60 requests/hour (unauthenticated), 5000 requests/hour (authenticated)
• Caching, Etag, Last-Modified all supported
• CORS allowed from any origin
• Documentation appears largely handwritten, with much descriptive prose and inline examples
• GitHub provides a client-access library (Octokit) to make using API easier
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 70 / 75

GitHub REST API Design Decisions
• Nontrivial searching (e.g. find me all repositories with size > 10000) require the use of a separate search endpoint, distinct from the normal collection endpoint
• There is no obvious, programmatic way for retrieving the schema of a particular resource.
• No way to control what fields are returned from the collection summary or item detail view
• What if you want to show a table of repositories that has a column which isn’t in the collection summary?
• What if you’re displaying the information on a single item and only need a few fields?
• What if an item detail field is expensive to calculate?
• What if you want to be able to parameterize an item detail field (e.g.
give me the value in a different currency)?
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 71 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 72 / 75

Stripe REST API
https://stripe.com/docs/api
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 73 / 75

Table of Contents
1 Last Week
Last Week Review
Homework 2 Review
2 REST
Simple API Case Study
REST API Design Considerations GitHub REST API Case Study Stripe REST API Case Study
3 Wrap-Up
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 74 / 75

Next Steps
• HW 3 is available now. It is due Tuesday, May 11 at 5:30PM.
• Quiz 3 is available now. It will be due Tuesday, May 4 at 5:30PM.
Steven Engelhardt (DePaul University) SE457 Week 5 – REST (Continued) Spring 2021 75 / 75