1 of 26

10 - React API.

Speck Academy 2021

2 of 26

API

AJAX

Fetch API

Async/Await

1

2

3

4

Overview

3 of 26

1

API

4 of 26

API

API - Application Programming Interface

Code that allows two software programs to communicate with each other.

Contract between a provider of some service and a client of those services which defines:

  • How is the data accessed
  • Who is authorized to access the data
  • Which data can be changed, how and by the whom
  • How is data formatted in the response, etc.

5 of 26

API

In most cases you’ll use APIs that are created in the way that REST architectural style defines.

REST (Representational State Transfer) is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.

6 of 26

REST

Separation of the client and server

  • Implementation of the client and server can be done independently without each knowing about other.
  • Code on the client side can be changed at any time without affecting the operation of the server, and vice versa.

Statelessness

  • The server doesn’t store any state about the client session on the server side. Each request from the client to the server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. The server never relies on information from previous requests.

7 of 26

REST

In the REST architecture, clients send requests to retrieve or modify resources, and servers send responses to these requests.

Request consists of:

  • An HTTP verb which defines what kind of operation to perform (GET, POST, PUT, DELETE)
  • A header, which allows the client to pass along information about the request. Type of content that client is able to receive from server (Accept parameter - application/json, text/html, image/jpg etc.)
  • A path to a resource that the operation should be performed on - /articles/12
  • An optional message body containing data

8 of 26

REST

Response consists of:

  • content-type if the server is sending a data payload to the client. This content type header field alerts the client to the type of data it is sending in the response body. These content types are MIME types, just as they are in the Accept field of the request header.
  • Response code that alerts the client about the success of the operation.
    • 200 (OK) - successful HTTP request
    • 201 (CREATED) - item successfully created, for example for POST requests
    • 204 (NO CONTENT) - nothing is being returned in the response body (DELETE)
    • 400 (BAD REQUEST) - bad request syntax or another client error
    • 403 (FORBIDDEN) - client doesn’t have permission to access the resource

9 of 26

REST

Let’s make some requests to the API.

In order to do that we can use Postman or Insomnia client (download Postman and try to make some requests to the routes specified inside Hands-on).

Together we will test requests that we will later implement in our React demo application.

You can find a lot of useful information about the REST architecture here.

10 of 26

2

AJAX

11 of 26

AJAX

AJAX stands for Asynchronous JavaScript And XML.

It is the use of the XMLHttpRequest object to communicate with servers.

It can send and receive information in various formats, including JSON, XML, HTML, and text files.

Asynchronous nature means it can communicate with the server, exchange data, and update the page without having to refresh the page.

It is well supported in all of the major browsers, even in old ones, such as Internet Explorer (check browser support for XMLHttpRequest API here).

12 of 26

AJAX

Instantiate XMLHttpRequest object and define how to process response from server inside onreadystatechange function.

First parameter of the open() function is the HTTP request method (GET, POST...) and second is the URL you’re sending the request to.

Any data you’re POSTing to server should be placed inside send() function.

13 of 26

AJAX

Inside AJAX request we can also have:

  • setRequestHeader() - in case we need to send additional headers, such as Content-Type for POST request, Authorization etc.
  • ontimeout() - timeout in milliseconds can be detected
  • upload.onprogress() - progress event can report on long-running file uploads
  • All options, events and response properties can be found here.

AJAX is quite a old implementation, but still offers us a lot of features. If you need to use traditional XHR then check jQuery.ajax() to make things easier.

Most popular modern alternatives to traditional XHR are Fetch API and Axios.

14 of 26

3

Fetch API

15 of 26

Fetch API

Fetch API provides an interface for fetching resources and it is a modern alternative to XMLHttpRequest.

Available in multiple interfaces (specifically Window and WorkerGlobalScope).

fetch() method returns a promise that resolves to the response of that request whether it was successful or not.

Fetch is clean, elegant, simpler to understand, but it is not a full drop-in replacement for traditional AJAX.

Fetch is quite a new in development, so please check browser support before use.

16 of 26

Fetch API

On the image on the right you can see example of GET request on the top of code.

The json() is a method of the body mixin that returns a promise that resolves with the result of parsing the body text as JSON.

Because json() returns a promise we can chain another then() which logs the parsed response

17 of 26

Fetch API

Uncommented code shows an example of POST request used for user registration.

  • This is a bit more complex than GET request.
  • Here we are using Content-Type which defines which type of data we are passing to server.
  • body defines data that we are sending, if we are sending JS object or value it must be wrapped by JSON.stringify method.
  • then() chaining is also used in order to get actual response from server.

18 of 26

Fetch API

fetch() allows us to make other types of requests as well like POST, PUT, DELETE and so on.

We can provide the headers (most often Content-Type or the Authorization), body of a request in case of POST and PUT requests.

If we compare Fetch and XHR:

  • Fetch returns successful call no matter if error exists, XHR returns error as expected.
  • Timeouts are not supported in fetch().
  • fetch() is Promise based and in case where we need to make call after another call we can use chaining of then() methods. In case of XHR, calls must be nested several layers deep.

19 of 26

4

Async/Await

20 of 26

Async/await

async and await are extensions of promises.

Asynchronous function operates asynchronously via event loop.

async use an implicit Promise to return its result. Even if you don’t return a promise explicitly, async function makes sure that your code is passed through a promise.

async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise’s resolution, and then resumes the async function and returns the resolved value.

await only can be used inside async function.

21 of 26

Async/await

Example explanation:

  • We’ve defined two async functions which return explicit promise, and our goal here is to create execution one after another.
  • In returnTimeoutsAwait() our async methods will be executed one after another, and inside returnTimeoutsPromises() will be executed paralel.
  • By use of async/await we can avoid ugly nesting.

22 of 26

Async/Await vs Promises

These two concepts are similar, but each of it has its own purpose.

  • Await blocks the execution of the code within the async function in which is located.
  • If the output of function2 is depenedent on output of function1 then use await.
  • If two function can be run in parallel create an array of promises and then use Promise.all().
  • Everytime you use await remember that you are writing blocking code (avoid too much blocking code).

Useful resources (please read):

23 of 26

5

Hands-on

24 of 26

Hands-on

25 of 26

6

Homework

26 of 26

Homework