> For the complete documentation index, see [llms.txt](https://gzqsjtu.gitbook.io/workspace/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gzqsjtu.gitbook.io/workspace/restful-api.md).

# Restful API

## Map CRUD to HTTP methods on a RESTful API

* Create - Post
* Read - Get
* Update - Put
* Delete - Delete

## The difference between PUT, POST and PATCH method

<https://stackoverflow.com/questions/630453/put-vs-post-in-rest/630475>

In **POST** method you can send body params in `form-data`

In **PUT** method you have to send body params in `x-www-form-urlencoded`

* **POST** to a URL **creates a child resource** at a *server defined* URL.
* **PUT** to a URL **creates/replaces the resource** in its entirety at the *client defined* URL.
* **PATCH** to a URL **updates&#x20;*****part*****&#x20;of the resource** at that client defined URL.

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-Li4_W_OLF-1qksm1RB0%2F-Li4_X89iTOgUwZ6JfsU%2Fimage.png?alt=media\&token=0f7c9262-3093-447a-afe2-c1b08dd2dee1)

**POST creates a child resource**, so POST to `/items` creates a resources that lives under the `/items` resource. Eg. `/items/1`. Sending the same post packet twice will create two resources.

**PUT** is for creating or replacing a resource at a **URL known by the client**.

Therefore: **PUT** is only a candidate for CREATE where the client already knows the url before the resource is created. Eg. `/blogs/nigel/entry/when_to_use_post_vs_put` as the title is used as the resource key

**PUT** replaces the resource at the known url if it already exists, so sending the same request twice has no effect. In other words, **calls to PUT are idempotent**.

## HTTP Status Code

* 1xx: Informational
* 2xx: Success
* 3xx: Redirection
* 4xx: Client Error
* 5xx: Server Error

## MVC vs Flux

MVC works both in server and client side development. MVC architecture: the user updates the controller, the controller manipulates the model, the model updates the view, and finally the user can see the view.

Flux is used for building client-side web applications. It implements React's com-posable view components by utilizing a unidirectional data flow.&#x20;

## Throw vs Reject

Any time you are inside a promise callback, you can use `throw`. However, if you are in any other asynchronous callback, you must use `reject`. Moreover, `reject` does not terminate control flow like a `return` statement does. In contrast `throw` does terminate control flow.

## AJAX in Reastful

AJAX (Asynchronous JavaScript and XML) is to create asynchronous web applications. With AJAX, web applications can send data and retrieve from a server asynchronously in the background without the need to reload the entire page.&#x20;

The `XMLHttpReques`t API is frequently used for the asynchronous communication or these days, the `fetch` API.&#x20;

## AJAX - pros & cons

Advantages:

* Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.&#x20;
* Reduce connections to the server since scripts and stylesheets only have to be requested once.&#x20;
* State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded.
* Basically most of the advantages of an SPA.

Disadvantages:

* Dynamic webpages are harder to bookmark.
* Does not work if JavaScript has been disabled in the browser.
* Some web-crawlers do not execute JavaScript and would not see content that has been loaded by JavaScript.&#x20;
* Basically most of the disadvantages of an SPA.&#x20;

## Cross Browser Compatibility Issues

Since difference browser may require different API for the same functionality, you can easily use if - else statement to define which API should be used in which environment. If the API is not working with that browser, it will return undefined.&#x20;

## Continuous Integration (CI)

Continuous Integration is a development practice that requires developers to integrate code into a shared repository several times a day. Each check-in is then verified by an automated build, allowing teams to detect problems early.&#x20;

## Cross-Domain Solution (CDS)

A cross-domain solution is a means of information assurance that provides the ability to manually or automatically access or transfer information between two or more differing security domains.&#x20;

## 5 ways to reduce the page loading speed

* Optimize Images
* Browser Caching&#x20;
* Compression
* Optimize Your CSS
* Keep the Scripts below the fold

## The workflow for JSON web token

#### Step 1. Create the **HEADER** <a href="#bb82" id="bb82"></a>

#### Step 2. Create the PAYLOAD <a href="#d7f1" id="d7f1"></a>

#### Step 3. Create the SIGNATURE <a href="#d5ea" id="d5ea"></a>

```
// signature algorithm
```

```
data = base64urlEncode( header ) + “.” + base64urlEncode( payload )
```

```
hashedData = hash( data, secret )
```

```
signature = base64urlEncode( hashedData )
```

#### Step 4. Put All Three JWT Components Together <a href="#id-309c" id="id-309c"></a>

```
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM
```

#### Step 5. Verifying the JWT <a href="#id-9c33" id="id-9c33"></a>

JWT that is signed by the HS256 algorithm

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-Lhgwlr1sK2R7MZL4CcZ%2F-Lhh0MCWZXS5WiA0tyPe%2Fimage.png?alt=media\&token=ae95b575-e772-4309-93f9-8ee7476ec6b8)

## How do you parse JSON in backend

use body-parser module

## Microservices&#x20;

Microservices - also known as microservice architecture - is an architectural style that structures an application as a collection of services that are&#x20;

* Highly maintainable and testable&#x20;
* Loosely coupled
* Independently deployable
* Organized around business capabilities

The microservice architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.&#x20;

## REST Security <a href="#rest-security-cheat-sheet" id="rest-security-cheat-sheet"></a>

#### HTTPS <a href="#https" id="https"></a>

This protects authentication credentials in transit, for example passwords, API keys or JSON Web Tokens. It also allows clients to authenticate the service and guarantees integrity of the transmitted data.

#### Access Control <a href="#access-control" id="access-control"></a>

#### JWT <a href="#jwt" id="jwt"></a>

&#x20;[JSON Web Tokens](https://tools.ietf.org/html/rfc7519) <https://jwt.io/>

```javascript
const tokenDecodablePart = token.split('.')[1];
const decoded = Buffer.from(tokenDecodablePart, 'base64').toString();
```

#### API Keys <a href="#api-keys" id="api-keys"></a>

* Require API keys for every request to the protected endpoint.
* Return `429 Too Many Requests` HTTP response code if requests are coming in too quickly.
* Revoke the API key if the client violates the usage agreement.

#### Restrict HTTP methods <a href="#restrict-http-methods" id="restrict-http-methods"></a>

* Apply an allow list of permitted HTTP Methods e.g. `GET`, `POST`, `PUT`.

#### Input validation <a href="#input-validation" id="input-validation"></a>

* Validate input: length / range / format and type.
* Achieve an implicit input validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters.
* Constrain string inputs with regexps.

#### Validate content types <a href="#validate-content-types" id="validate-content-types"></a>

#### Security Headers <a href="#security-headers" id="security-headers"></a>

The following headers should be included in all API responses:

| Header                                            | Rationale                                                                                                                                   |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `Cache-Control: no-store`                         | Prevent sensitive information from being cached.                                                                                            |
| `Content-Security-Policy: frame-ancestors 'none'` | To protect against [drag-and-drop](https://www.w3.org/Security/wiki/Clickjacking_Threats#Drag_and_drop_attacks) style clickjacking attacks. |
| `Content-Type`                                    | To specify the content type of the response. This should be `application/json` for JSON responses.                                          |
| `Strict-Transport-Security`                       | To require connections over HTTPS and to protect against spoofed certificates.                                                              |
| `X-Content-Type-Options: nosniff`                 | To prevent browsers from performing MIME sniffing, and inappropriately interpreting responses as HTML.                                      |
| `X-Frame-Options: DENY`                           | To protect against drag-and-drop style clickjacking attacks.                                                                                |

#### CORS[¶](https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#cors) <a href="#cors" id="cors"></a>

Cross-Origin Resource Sharing (CORS) is a W3C standard to flexibly specify what cross-domain requests are permitted. By delivering appropriate CORS Headers your REST API signals to the browser which domains, AKA origins, are allowed to make JavaScript calls to the REST service.

* Disable CORS headers if cross-domain calls are not supported/expected.
* Be as specific as possible and as general as necessary when setting the origins of cross-domain calls.

#### &#x20;<a href="#input-validation" id="input-validation"></a>
