REST - LinkedIn Learning Flashcards

1
Q

Which are the broad steps for designing API?

A

API design is hard and is a game of tradeoffs.

1) Decide what functionality to expose by understading the domain and customer requirements
2) Decide how to expose it
3) Decide the best ways to expose it
4) Test and (in)validate the assumptions
5) Repeat

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which are the three different aspects in play when designing API?

A

1) What the API does
2) What the API makes easy
3) What the user wants to do
We need to strike balance and align these three to make a powerful API which is easy to use.

Example of coffee mug, suppose the mug didn’t have a handle then it tends to get hot, but after handle you can use it without burning your hand. The good thing about handle is that you can also use it to hang it on a hook.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do we add an API?

A

There are three different scenarios

1) Bolt-On strategy - Brownfield. When you already have something running and you create API for that.
2) Greenfield Strategy - For new systems
3) Facade strategy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is Bolt on strategy and what are pros and cons of Bolt on strategy?

A

Bolt on strategy is useful for existing applications when you already have an application and add an API after that fact.

Pros

1) Fastest way - Brute force approach
2) You have everything already running all the time

Cons
1) Bad naming conventions, architecture of the past get reflected in API and client libraries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Greenfield strategy and what are its pros and cons?

A

Greenfield strategy is useful for new systems where there is no application or business logic yet to interact with. We have complete flexibility to design API.
This is the “API first” or “Mobile First” approach.

Benefits

1) Easiest to develop API
2) Can take advantage of new technologies and architectures that reinvigorates the team.

Cons
1) Hardest option as there can be big gap from when you receive requirements and when you actually receive value from the system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Facade strategy and what are pros and cons?

A

Facade is recommended approach, and is somwhere between greenfield and brownfield
We take advantage of existing system and yet shape them to what you prefer and need.

Benefits

1) Ability to rearchitect existing SOAP services with new REST interfaces.
2) The application is always functional, while making the underlying architecture better

Drawbacks

1) It can be challenging to have “multiple mindsets” in the system
2) There can be many conversion layers that can easily get out of control.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Steps for the API modelling process

A
1 - Identify the participants
2 - Identify Activities
3 - Break into steps
4 - Create API definitions
5 - Validate your API
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Describe Step - Identifying the participants

A

Participants are the ones who will be involved in the business process that eventually uses the API. Participants are not only humans, they can be IoT devices, monitoring services etc also. So not all the participants will be humans.

Who/What is involved in our business process.

  • Anyone who initiates the action
  • Anyone who waits for an action to occur (receives action as a result of an event)

For each participant we need to understand

  • Who they are (Give them a name and personna)?
  • Are they internal or external (will it be used by other team in our organization or outside)?
  • Are they active or passive participants?
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What can be said about decision of system boundaries when designing API?

A

We should be very careful and clearly identify what we are responsible for and what are other, even third party coponents.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe Step - Identify Activities by taking an example of ordering a coffee

A

Revision 1 (Very simplistic view and abstract)
- Place an order
- Wait for the coffee
- You receive the order
The revision 1 does not go into the activities and the participants involved.

Revision 2

  • The patron or you place the order with the cashier
  • The cashier passes the order to the barista
  • The barista acknowledges the order and adds it to the queue
  • The cashier tells the patron their total bill
  • Parton provides the payment, which is either accepted or rejected
  • If rejected, patron needs to choose different payment method
  • The barista makes the orders and delivers them to patron.

This paints much more complete picture of what is happening. It highlights the participants and the dependencies and the order in which actions occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Identifying participants and activities to order a book online

A

Identiying the participants of ordering book online process

  • Customer
  • System administrator (X) No role in this activity
  • Developer (X) No role in this activity
  • Stock Clerk (who fulfills the actual order)
  • Customer support (just in case there is issue in ordering the book or the books are out of stock and inventory count is not accurate)

What are the activities?
1 - Customer searches for the book (so we need some mechanism for customer to search what he needs)
2 - The customer adds the book to their cart
3 - The customer adds more things? Removes things? (we need this functionality in future, but we are focused on ordering a book online. So we make a note document it that we will figure it out later and contact product owner to clarify things)
4 - The customer checks out
5 - The stock clerk retrieves and ships the book
6 - Customer support contacts the customer about the book in case it is out of stock and inventory details were not accurate, to either cancel the order or make some other arrangements.

So summary
1 - View items (search items)
2 - Add item to the cart
3 - Add more items? Remove items?
4 - Check out (including payment)
5 - Fulfill and ship the order
6 - View order
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Describe the step - Creating API methods using example of ordering book online

A

First from the steps leave out the steps that are outside of scope of what you are tacking right now. This is where experience comes in and it more of a art.

FIND RESOURCES
Resources are anything someone wants to interact with in our system or another way is finding out NOUNS.

In book ordering case these are the resources

  • Items (view, edit or add items) so similar to CRUD
  • Cart - here we have design decision, either the cart is collection of items or is there a line item resource or object that holds individual item. We choose cart as collection of items. So adding or removing we just have to change the state of cart.
  • Orders - order is simply a cart which has undergone the checkout process.
  • Customer (hidden) - because to checkout we will need customer details but that detail we can figure out later and contact product owner about this.

We have not defined the checkout process, because it will be part of other story and will fill the details, currently we just know that checkout will either succeed or fail.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which HTTP verb is used to get collection of resources?

A

HTTP GET is used for this. We should never modify information in this method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which HTTP verb is used for deleting?

A

HTTP DELETE is used for deleting resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which HTTP verb is used for updating the information of resource?

A

HTTP PUT is used for updating the existing resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which HTTP method is catch-all or default for something that doesn’t fit in any of methods?

A

HTTP POST is used for creation, to change the status/state of a resource. Used for anything which doesn’t cleanly map or fit the GET, PUT, DELETE verbs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Define step - Creating API - Map the actions with HTTP verbs

A

Item resource

  • Get Items (HTTP GET)
  • Get Item (HTTP GET)

Cart resource (2 ways to see this - design and modelling decision)

1) Are we creating and then adding an item
- Create Cart (HTTP POST because we are creating a cart)
- Add item to Cart (HTTP POST because we are creating links between our cart and existing items)
- Check out

2) Are we creating a cart and then modifying the cart to add/remove items to it
- Create cart (HTTP POST because we are creating a cart)
- Add item to the cart (HTTP PUT because we are modifying the attributes of cart to add/remove item to it)
- Checkout (HTTP POST because it doesn’t cleanly fit into any of the GET, PUT, or DELETE verbs)

Order resource

  • Create order (No need, probably done by checkout process)
  • View order (HTTP GET)
  • Cancel order (HTTP POST and not DELETE because we are not deleting the order but we are changing/modifying its status to cancelled)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Describe the types of relationships that resources can have

A

Independent
Can exist on its own without any other resources

Dependent
Can only exist if another resource already exists. Like in book ordering scenario, an order cannot exist without a cart previously existing.

Associative
Can be dependent or independent but needs additional information to describe it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Describe the types of relationships between resources by taking example of movies and actors

A

Independent
Movies and Actors
are independent because we can one movie and one actor or we can have many movies and many actors.

Dependent
Movies and Characters
are dependent because a particular character cannot exist outside the movie.

Associative
One actor playing multiple characters in the same movie
or multiple actors playing role of same character (as teenager, child and adult). So just saying this actor plays this character isn’t enough, we need to say that this actor plays this character ‘as a child’ to fully understand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Describe the types of relationships between resources by taking example of book ordering

A

Items are independent (don’t need cart or orders or customers to have items)

Cart is dependent on Items (can’t have a cart without items)

Orders are dependent on cart (only after we have a cart can we have order that is created by cart checkout process)

Orders are dependent on customers (there is actually a customer signed in who has ordered)

So by doing this exercise we get a dependency graph.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Is it a good practice to design API based on database design?

A

No it is not a good practice. Because first we are exposing the underlying database schema and secondly the choices that go into designing database are not same that go into designing API.
The ways with which people or customer interact with your API don’t map one to one with database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Describe the step - Validating the API

A

Bad approach will be to start building the API to validate it. But it may waste months of efforts, so it’s a bad idea.
So we need a method to validate that is faster, cheaper.

1 - Post it cards/steps to map other use cases
If we can achieve other use cases with these steps then great, if not figure out which step is missing. After all we make these steps from activities, so everything must map cleanly together, if it doesn’t then that’s a red flag. We need to go steps back and make sure things work.

  1. Write code but not for API but client code which will behave as if API already existed. This will highlight major issus or structure issues.
  2. Use a microframework (hapi.js, slim in PHP) to create mock APIs (BEST APPROACH)
    You can accept incoming requests and validate the verbs and URL patterns
    We can send static HTTP response codes and payloads.
    This appraoch is recommended because as we built things, we can start replacing those mock responses with real endpoints and watch things come together.
  3. Documentation
    Write the documentation as if the API already exisits.
    - List endpoints - describe what they do
    - List the parameters - describe what they mean
    - List the response codes - describe when you get each
    - Show the response payloads - define the fields
    Goal is to write documentation that we can share with other teams that helps them in accomplishing their goals. It is good practice to include curl calls to show what calls look like.
    But there are drawbacks of this approach
    - Trying to be perfect. Instead we just need to be concise but not perfect.
    - Documentation is last step, so people may think that the project is complete. So we need to clarify that documentation is for validation purposes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is REST? Is it a standard or specification?

A

REST is a generally agreed upon set of principles and constraints. It’s not a specification or a standard. Which provides for a ton of flexibility. The downside is that there is not always a right answer. But REST concepts are based on a set of standards.
For analogy,

SOAP (Getting mortgage) | REST (borrowing money from friend)
- fixed process | - few requirements
- Lots of documentation for | - No documentation, you learn and evolve as you go
each step | - Flexibility, based on needs of you and party
- Detailed scenarios of | - Flexible, based on patterns
possibilities
- Complex error handling
if something doesn’t go
right

24
Q

What does an HTTP request and response consist of?

A

HTTP Request - Header (Method + URL + Query Parameters) + Payload (XML or JSON or some other)
HTTP Response - Header (Response Code) + Payload

25
Q

Describe various 2XX HTTP response codes

A

2XX are successful category of response codes in HTTP.

200 - OK
General means request was successful

201 - Created
Returned when the resource has been successfully created. Like when creating a shopping cart is successful

202 - Accepted
Returned when the process has started but not fully processed yet. This is used in systems which use some asynchronous processing or queuing. When the work will be started, or is in progress but is not yet done.

204 - No content
Returned when you delete a resource. Because we just deleted the resource and we can’t show it now.

26
Q

Describe various 3XX HTTP response codes

A

3XX category response codes are used when a resource moves from it’s original URL.

301 - Moved permanently
The resource you are looking for has been permanently moved to some different URL. Most of the APIs will give the URL in response which can be used to retrive the resource

302 - Moved temporarily
Instead of keeping that URL permanently, we need to keep checking periodically if the old URL is available now.

27
Q

Describe various 4XX response codes

A

4XX is failure category. They are very important because when used properly the API can be very descriptive with just a few bytes.

400 - Bad Request
The request failed due to the client itself. This is very generic and whenever possible we must choose a specific response code.

401 - Authentication Required
Doesn’t say whether the operation was successful or not but just says that authentication is required before the opreation can be done.

403 - Forbidden
In this case the authentication was successful, the request was well formed and understood but was explicitly failed because the user doesn’t have necessary priviledges do perform that operation.

404 - Not Found
Returned when the resource doesn’t exist. It doesn’t mean it did exist and you didn’t find it. It means that it “DOES NOT EXIST”.

28
Q

Describe classes of HTTP response codes

A
1XX - Informational
2XX - Success
3XX - Redirect
4XX - Client Error
5XX - Server error
29
Q

Describe the Content-Type header

A

Identifies the type of payload being provided by the server. For normal web browsing it will be text/HTML but for APIs it will be application/json or text/XML.
NOTE: This only describes what the payload is and not how it’s structured.
For structure we need to check other header Media-Type

30
Q

Describe Media-Type header

A

Media types are specifically named and structured payloads that allow a client to be customized to handle them.
For example of github.com API
X-GitHub-Media-Type: github.v3; format=json
tells us that its GitHub media type version 3.

There are specifications for Media types which are under development.

31
Q

What is the response code header called in HTTP?

A

Its called “Status” header. So you will hear commonly like status 404 etc.

32
Q

Explain 6 REST API constraints

A

These constraints are design guidelines and not hard and fast rules.
If not followed it makes API harder to understand.

1 - API should be designed for client-server architecture.

2 - API should be stateless.

3 - Cacheable

4 - Layered Systems

5 - Code on Demand (optional) very powerful

6 - Uniform Interfaces (Most important)

33
Q

What is idempotency? Give some example of Idempotent API and Non idempotent API

A

You do same operation multiple times and you get the same result everytime.
Example of idempotent API will be view github repository. Even if we fire it multiple times the result will be the same.
In case of create user API, it is not idempotent. If we send N requests we create N users.

34
Q

Describe Uniform Interfaces design guideline

A

4 key principles make uniform interfaces

  1. Identifiable Resources
    Each resource should be uniquely addressable by a particular URL. Generally there will be one and only one way to access this resources. But it is not a hard requirement.
  2. Manipulate Resources through these representations
    Every interaction with a given resource should happen through identifier we already gave it.
    NOTE: This isn’t just about adding an ID parameter at the end of the URL. But having the ID is part of the URL. Its subtle distinction.
  3. Self descriptive messages
    By making messages standalone with their own caching and processing information we can create and use different types of messages very easily. Our client only needs to know how to retrieve and execute those instructions.
  4. Hypermedia as the engine of application state (HATEOAS)
    Fundamentally its a choose your own adventure book.
    You don’t read pages sequentially like one, two, three. When faced with choice you can read one page for choice one and different page for other choice.
    At every point in API that are different things you can do and the links are contained and available with response in API. So don’t need to refer documentation. Like if you hit GitHub api
    curl https://api.github.com
    You will get in response URLs of all the APIs available. So the application doen’t need to remember how to create user URL it can just ask the API for the URL that is based on it’s name.
    This allows for “link discovery”. The applications don’t need to remember URL beforehand, but can just discover them like we as humans do.
35
Q

Describe Code on Demand design guideline

A

When the client requests a resource with resource it also receives code to act upon it. The client doesn’t need to know what is in the code, it just needs to know how to execute it.
The benefit is that APIs can grow and extend without requiring clients to upgrade. Just like web applications and Javascript. Browsers just need to know how to execute javascript. No need to upgrade the browser if the web application changes.

36
Q

Describe Layered Systems design guideline

A

Client should not be built with assumption that it’s communicating directly with the server. There can and will be multiple layers between client and server. There can be caching, firewall, API gateway, load balancing etc.
Layers give us flexibility to improve and evolve our system as requirements and our architecture changes.

37
Q

Describe Cacheable design guideline

A

Each request describe if it can be cached and for how long. Advantage of caching is to improve network performance and application usage overall. By reducing and sometimes eliminating requests.
GET, PUT and DELETE should be “idempotent” or “same”. Like viewing your github repository. You keep firing same API and nothing will change.

But it is not the case with POST - create user API, you send one request you create one user, if you send N requests you create N users. So create user opreation is not idempotent.

38
Q

Describe Stateless design guideline

A

Every request can stand on its own (self-contained) and be processed or rejected independently of any other request.
Practically it means that sending credentials with each and every request. Because we can’t count on the logon request to reach there before the subsequent requests.
The ability to process requests independently of each other allows us to isolate request failures and still scale systems better. No shared state, sticky sessions etc.

39
Q

Describe AuthN and AuthZ process

A

AuthN - Authentication which establishes who I am
AuthZ - Authorization which establishes what I am allowed to do. Like subscription level, admin or user, group membership.

40
Q

Which are three main design patterns for AuthN and AuthZ

A
  1. API keys
  2. Roll your own AuthN/AuthZ protocol
    Absolutely worst option and must never be done. No benefits and huge drawbacks and security flaws.
  3. OAuth and OpenID connect
41
Q

Describe API Keys design pattern for AuthN/AuthZ

A

Long string issued by API URL which must be appended in request in header or URL.

Benefits
Framework and language agnostic
Easy to add as a header or even to URL

Cons
URLs are convinient but are logged everywhere (not a secret) and not secure. If part of header then much better but then to easy to update if compromised. We may have to redeploy all the applications.

42
Q

Describe OAuth and OpenID Connect design pattern for AuthN/AuthZ

A

Well established standard used by most of APIs

Benefits
Reliable and well established
Massive ecosystem
Open-source and commercial options

Drawbacks
Complicated and not easy to implement the first time.

43
Q

Which are two different ways to address API versioning?

A
  1. Versioning by URL
  2. Versioning by Accept Header
    No matter what option we choose we can’t eliminate content negotiation.
44
Q

Explain the Accept Header way of versioning the API

A

With Accept header the client and the API can negotiate which version (structure) it is expecting. This is a good option but it has disadvantage that from URL you cannot make out which version you are going to get. So we lose clarity.

45
Q

What is Accept Header in HTTP?

A

It is used for Content Negotiation. It establishes the markup notation. At first level it can be as simple as XML or JSON.
Can establish the media type (structure of the markup).
Can establish the version of the media type (and resource)

46
Q

What is Media type?

A

Media type is just a well defined structure that the client and API understand. Media type allows us to use commonly structured JSON file to moe data back and forth. The media types are in growing adoption.

47
Q

Explain the URL way of API versioning

A

Clear and explicit - When we look at the URL we can exactly tell what the developer is asking for and expecting.
Nothing is lost in copy and pasting

48
Q

When does the need arises to change the version

A

When we break backwards compatiblity.

49
Q

What are different content types possible for payload in REST?

A
  1. Name/Value pairs and JSON - Yes, its easy and works. But it gets harder to extend and almost impossible to add detail about the data.
  2. Custom format
    We will not build our own Image or Audio format, they why do that with JSON. So we use Media type.
  3. Media type
50
Q

Which are different Media Types?

A
  1. Collection + JSON
    Designed specifically to deal with groups or collections of resources. Designed to hande read/write operations., to query a set of objects and manipulate them.
  2. Hypertext Media Language (HAL)
    It breaks the data payload into two pieces. First it represents the data structure of the resource. Second it has a underscore to links section which gives us references to other related resources and how to interact with those.

Advantage

  • This is close to choose your own Adventure
  • HAL has been around for a while there are libraries and utilities available that may be helpful.

Drawbacks

  • It can be verbose.
  • Just like footnotes, the _links section may get unnoticed and never explored.
  1. Ion Hypermedia Type
  2. Many other and there is no one right answer.
51
Q

What is Hypermedia?

A

Hypermedia us a combination of two concepts Hyper + Media.
Media - Information can exist in different formats. Like watching favourite game, there can be .mov live streaming, .mp3 announcers commentary on radio, .txt summaries before and after, .mp4 video clips of highlights and pivotal moments, .jpg diagrams of particular place or events of the game. This is what multi-media experience means, that it can deliver rich experience that can appeal to variety of audiences in variety of ways.

Hyper - Means the media isn’t linear - beginning, middle and end don’t necessarily mean anything in this context.. Just like Quora, you may start website from one question but then go from that to any other random and there is no/very few fixed paths.

52
Q

Good APIs to refer for HyperMedia and reference

A

GitHub, Twilio, Okta etc

53
Q

What is Content negotiation header?

A

The mechanisms allow different versions of same document to exist at a single URL so the client-server can determine which version best fits their capabilities.
The client says here are the formats I support and server says great I can support one of these. Let’s continue. This happens implicitly behind the scenes.

54
Q

What is Caching Header?

A

A way of storing and retrieving the data so that future requests can retrive it faster without performing an operation.
ETag header is generated by server and returned to the client. It is a hash.
1) Client makes a request
2) server generates a response and includes ETag based on resource state (it is a hash of response mostly)
3) Before client makes next request, it uses the HEAD verb to just get the headers, including the ETag.
4) If data is unchanged server returns the same ETag. Client recognizes this and request is complete. This saves retrieving and reparsing of data.
5) If data has changed then server returns a new ETag.
6) If ETag has changed then client makes the full request.

55
Q

Goals for API documentation

A

1) Code snippet friendly as they are API docs
2) We need version control. As things change, improve or expand we need to put same rigor into our documentation review, like code reviews. If API is revenue generating then mistakes here will cost you money.
3) Should be easy to update
4) Searcable - if we can’t find it, it doesn’t exist. Not only internally on the site, but Google should be able to crawl too.

56
Q

Tools for API documentation

A

MediaWiki,
Confluence,
Jekyll (static site generator),
Slate

57
Q

Describe SPOIL term for great user experience with SDKs and APIs

A

S - Succinct
It should be concise but precise

P - Purposeful
SDKs should be as carefully designed like APIs

O - Open Source
Encourage wrappers, extensions and user contributions

I - Idiomatic
Language based idoms should be used.

L - Logical
SDK should be logical. Lessons learned or common patterns are repeated elesewhere.