Workspace
  • Study Book
  • WEB Network HTTP etc
    • Performance Optimization
    • Performance Optimization
    • HTTP/2 & SPDY
    • WebSocket
    • HTTP Header
    • Cross-Origin Resource Sharing
    • JSON, XML, other format
  • Javascript
    • Promise
    • make API call
    • Web API
    • Common JS
    • AJAX
    • Event DOM and delegation
    • ES6 new features
    • special function
    • function API
  • React
    • class component
    • Example
    • Lifting functions/ state up
    • Hot Loader
    • Testing
    • New Features
    • Hook
    • Simple code
    • Life Cycle
  • CSS
    • Horizontal & Vertical Align
    • GPU Animation
    • transform-function
    • LVHA Pseudo-classes
    • Selector
    • How To CSS
  • HTML
  • Redux
  • NodeJS
    • File System
  • express
    • express questions
    • express mongodb
  • Restful API
  • MongoDB
  • Compare
  • Test
    • Jest
  • Deploy development
  • coding question
  • DevOps
  • Webpack
  • GraphQL
Powered by GitBook
On this page
  • Map CRUD to HTTP methods on a RESTful API
  • The difference between PUT, POST and PATCH method
  • HTTP Status Code
  • MVC vs Flux
  • Throw vs Reject
  • AJAX in Reastful
  • AJAX - pros & cons
  • Cross Browser Compatibility Issues
  • Continuous Integration (CI)
  • Cross-Domain Solution (CDS)
  • 5 ways to reduce the page loading speed
  • The workflow for JSON web token
  • How do you parse JSON in backend
  • Microservices
  • REST Security

Was this helpful?

Restful API

Previousexpress mongodbNextMongoDB

Last updated 2 years ago

Was this helpful?

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 part of the resource at that client defined URL.

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.

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.

The XMLHttpRequest API is frequently used for the asynchronous communication or these days, the fetch API.

AJAX - pros & cons

Advantages:

  • Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.

  • Reduce connections to the server since scripts and stylesheets only have to be requested once.

  • 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.

  • Basically most of the disadvantages of an SPA.

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.

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.

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.

5 ways to reduce the page loading speed

  • Optimize Images

  • Browser Caching

  • Compression

  • Optimize Your CSS

  • Keep the Scripts below the fold

The workflow for JSON web token

Step 1. Create the HEADER

Step 2. Create the PAYLOAD

Step 3. Create the SIGNATURE

// signature algorithm
data = base64urlEncode( header ) + “.” + base64urlEncode( payload )
hashedData = hash( data, secret )
signature = base64urlEncode( hashedData )

Step 4. Put All Three JWT Components Together

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJiMDhmODZhZi0zNWRhLTQ4ZjItOGZhYi1jZWYzOTA0NjYwYmQifQ.-xN_h82PHVTCMA9vdoHrcZxH-x5mb11y1537t3rGzcM

Step 5. Verifying the JWT

JWT that is signed by the HS256 algorithm

How do you parse JSON in backend

use body-parser module

Microservices

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

  • Highly maintainable and testable

  • 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.

REST Security

HTTPS

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

JWT

JSON Web Tokens https://jwt.io/

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

API Keys

  • 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

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

Input validation

  • 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

Security Headers

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'

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¶

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.

To protect against style clickjacking attacks.

drag-and-drop