What is React API?
React API i.e. Application Programming Interface interacts among multiple software intermediaries. The kind of calls and requests to be made are defined by API. It also manages how to make those calls or requests, data formats to be used, conventions to follow, etc. Users can extend functionality in various ways with the help of API. It will provide an extension mechanism to do so. APIs allow users to use the interface independently of the implementation with the help of information hiding.
What is the API in react?
React is the entrance for the react library. There are two Top-Level APIs to react globally. If you want to write “import React from ‘react’ “, then you’ll need to use ES6 with npm. If you use ES5 with npm then you’ll need to write “var react= require (‘react’)”.
How to use API in React?
Representational State Transfer API (Restful API) is the most popular type of Web API. It uses an architecture that can perform predefined and stateless operations to access web resources. HTTP requests are important for using web API. There are different types of requests in API of which some are:
- Get: Using this, data requests are made from the end-point.
- Post: This function sends or transfers data to the end-point.
- Delete: It is used to remove the data from the end-point.
- Patch: Data value or record is updated at the end-point using this function.
These types of API are called External APIs as the interactions are external from the local environment.
There’s another API in react which you’ll see i.e. Context API. It is still an experimental feature and appeared to be safe in React’s version 16.3.0. This API solves one major problem i.e. prop drilling. React developers will only need to check whether everything works out perfectly when components will receive props indirectly.
We will learn the proper usage of API in react later. Before that, we will see some important topics related to API.
What are the keys to API?
APIs offer both data and services together or individually. Accessing APIs is an important thing and you may need to buy subscriptions for it. But there still are a lot of APIs available for free. It is useless to call an API an unlimited number of times in software. It is because External APIs do not have unlimited resources. There are secret API keys which will monitor the usage by API providers.
What are HTTP APIs?
API keys can be sent in multiple ways for HTTP-based APIs.
In the query string:
Post /something?
api_key= abcdef12345 HTTP/1.1
As a request header:
GET /something HTTP/1.1
X-API-Key: abcdef12345
As a cookie:
Get /something HTTP/ 1.1
Cookie: X-API-Key= abcdef12345
Operations with React API:
Data configuration
import { schema } from ‘normalizr’;
import { createStore, applyMiddleware, combineReducers } from ‘redux’;
import { configure, reducer } from ‘react-api-data’;
import thunk from ‘redux-thunk’;
const authorSchema = new schema.Entity(‘Author’);
const articleSchema = new schema.Entity(‘Article’, {
author: authorSchema
});
const endpointConfig = {
getArticle: {
url: ‘http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId/:userId’,
method: ‘GET’,
responseSchema: articleSchema
},
saveArticle: {
url: ‘http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId’,
method: ‘POST’,
afterSuccess: ({ dispatch, request, getState }) => {
dispatch(invalidateRequest(‘getArticle’, {articleId: request.params.articleId, userId: getState().userId}));
}
}
};
const store = createStore(combineReducers({apiData: reducer}), applyMiddleware(thunk));
store.dispatch(configure({}, endpointConfig));
API data Binding
import React from ‘react’;
import { useApiData } from ‘react-api-data’;
const Article = (props) => {
const article = useApiData(‘getArticle’, { id: props.articleId });
return (
<>
{article.request.networkStatus === ‘success’ &&
<div>
<h1>{article.data.title}</h1>
<p>{article.data.body}</p>
</div>
}
</>
);
}
Posting data
import React, { useState } from ‘react’;
import { useApiData } from ‘react-api-data’;
const PostComment = props => {
const [comment, setComment] = useState(”);
const postComment = useApiData(‘postComment’, undefined, {
autoTrigger: false,
});
const { networkStatus } = postComment.request;
const onSubmit = () => {
postComment.perform({ id: props.articleId }, { comment });
};
return (
<>
{networkStatus === ‘ready’ && (
<div>
<input
onChange={event => setComment(event.target.value)}
placeholder=”Add a comment…”
/>
<button onClick={onSubmit}>Submit</button>
</div>
)}
{networkStatus === ‘loading’ && <div>Submitting…</div>}
{networkStatus === ‘failed’ && (
<div>
Something went wrong.
<button onClick={onSubmit}>Try again</button>
</div>
)}
{networkStatus === ‘success’ && <div>Submitted!</div>}
</>
);
};
Removing API data from stores
import { useActions} from ‘react-api-data’;
const LogoutComponent = props => {
const actions = useActions();
return (
<>
{/* … */}
<button onClick={() => actions.purgeAll()}>Logout</button>
</>
);
}
Uploading a file:
const connectApiData = withApiData({
items: ‘getItemsInList’
}, (ownProps, state) => ({
items: [{listId: 1}, {listId: 2}, {listId: 3}]
}));
const ItemsList = (props) => {
if (props.items.every(item => item.request.networkStatus === ‘success’)) {
return (
<ul>
{props.items.map(item => (<li>{item.data.title}</li>))}
</ul>
);
}
return <p>Loading…</p>;
}
export default connectApiData(ItemsList);
Removing API data from stores
import { useActions} from ‘react-api-data’;
const LogoutComponent = props => {
const actions = useActions();
return (
<>
{/* … */}
<button onClick={() => actions.purgeAll()}>Logout</button>
</>
);
}
Including cookies with requests:
export const globalConfig = {
setRequestProperties: (defaultProperties) => ({
…defaultProperties,
credentials: ‘include’,
})
};
Using data parameters
const endpointConfig = {
getData: {
url: `${BASE_URL}/:language/getData.json`,
method: ‘GET’,
defaultParams: {
language: ‘en’,
},
},
};
Caching API responses:
export default {
getArticle: {
url: ‘http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId/:userId’,
method: ‘GET’,
cacheDuration: 60000, // 1 minute
},
getComments: {
url: ‘http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId’,
method: ‘GET’,
cacheDuration: 0, // no caching, use with caution. Preferably set to a low value to prevent multiple simultaneous calls.
},
getPosts: {
url: ‘http://www.mocky.io/v2/5a0c203e320000772de9664c?:articleId’,
method: ‘GET’
// Infinite caching
},
}
Including cookies with requests:
export const globalConfig = {
setRequestProperties: (defaultProperties) => ({
…defaultProperties,
credentials: ‘include’,
})
};
Conclusion:
API defines interactions among multiple software intermediaries. It manages how to make calls or requests, data formats to be used, conventions to follow, etc. There are two top-level APIs to react. The most popular type of API used is Restful API. Some of the HTTP requests for API are Get, Post, Patch, Delete, etc. These types of APIs are called External API. There’s one more API in react named Context API. This API is best for solving Prop drilling issues. There are secret API keys that monitor API usage by API providers. Thus it is of no meaning that one will call API unlimited times as they do not have unlimited resources. HTTP APIs can be found in Query String, Request Header, and Cookies. Some of the operations that can be done with the help of API are mentioned above.