Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 2, 2020 03:43 pm GMT

How to make API calls in React?

Do you know what Facebook, Google, GitHub, and thousands more APIs have in common? They use OAuth to authenticate requests.

OAuth, especially OAuth 2.0, is now everywhere. It's a very powerful authentication framework that powers up developers to have granularity over the data that it needs.

React + OAuth =

When it comes to OAuth-based API, your React app is not well-suited to send requests. You just can't hide your API keys deep into your codebase. Someone will easily find it.

What you need to do is to set up some backend service, that proxies requests to the third-party API. It can be fun to do, but it's a long process for a quick API call.

For example, you will need a backend to protect your API keys. Declare routes, understand packages (like Passport.js), proxying requests, and dozens of more actions. It doesn't have to be so hard.

Today, I'll showcase an open-source project that I'm actively contributing to. It's called Pizzly and it helps a lot with using API from a single page application.

Let's see how it looks like with a simple demo:

Curious about how you can do it on your application? Here's a full guide.

The React skeleton

To learn how to make API calls to an API, we first need a React skeleton. And the least that we need is an app that consumes an API endpoint using OAuth2.

As you probably have a GitHub account, we will use that API, but you can easily switch to any other API that uses OAuth2 (Slack, Salesforce, ...) or OAuth1 (Twitter, Trello, ...).

Here's how the application will look like:

import React from "react";import Pizzly from "pizzly-js";import Pizzly from "pizzly-js";export default class App extends React.Component {  constructor() {    super();    this.state = { profile: null };  }  render() {    return (      <div className="App">        <h1>Hello!</h1>        <p>          Click the button bellow to retrieve your GitHub profile using{" "}          <a            target="_blank"            rel="noopener noreferrer"            href="https://github.com/Bearer/Pizzly"          >            Pizzly          </a>          .        </p>        <button          onClick={() => {            this.connect();          }}        >          Retrieve your GitHub profile        </button>        <Profile profile={this.state.profile} />      </div>    );  }}

It's a very basic React application that renders the user's profile as a plain JSON when it has been fetched. Otherwise, it asks the user to connect to GitHub.

The authentication

Here, we gonna use Pizzly, the open-source project I told you about a few lines above.

It provides a .connect() method that triggers an authentication flow from your frontend, which you can handle with callbacks. No need to create a redirect URL, deal with backend, etc.

Let's see how to update the skeleton above to use with Pizzly:

export default class App extends React.Component {  constructor() {    super();    // Initialize Pizzly    const pizzly = new Pizzly({      host: PIZZLY_HOSTNAME,      publishableKey: PIZZLY_PUBLISHABLE_KEY    });    // Save the GitHub integration config, for later use    this.github = pizzly.integration("github", {      setupId: PIZZLY_SETUP_ID_GITHUB_DEMO_APP    });    this.state = { profile: null };  }  /**   * The connect method lets us authenticate a user   * to our GitHub application (i.e. the OAuth dance)   */  connect() {    console.log("Connecting to GitHub...");    this.github      .connect()      .then(({ authId }) => {        console.log("Sucessfully connected!", authId);        this.fetchProfile(authId);      })      .catch(console.error);  }  render() {    // ...  }}

That's it. A few lines of code in your application and you are ready to handle any OAuth based API .

The configuration

Pizzly is a self-hosted OAuth manager. This means that you need to host it somewhere, for example on Heroku (it takes 30 seconds). Once hosted, you can access Pizzly's dashboard, which is where you configure your GitHub integration.

Pizzly dashboard

To deploy your own Pizzly instance right now, click on any of the following button:

HerokuPlatform.sh
Deploy to HerokuDeploy with Platform.sh

Then, select the GitHub API. And configure it by saving your application's client ID, client credentials and scopes. You will get them from GitHub by following this guide.

Once your Pizzly instance is created and you have configured a GitHub application, edit your React application with the following values:

// Pizzly environment variables, ake sure to replace// these with those of your own Pizzly instanceconst PIZZLY_HOSTNAME = "";const PIZZLY_PUBLISHABLE_KEY = "";const PIZZLY_SETUP_ID_GITHUB_DEMO_APP = "";

The least that you need is PIZZLY_HOSTNAME. The two others are optional.

An authenticated API request

Alright, we have already spend a few minutes on the configuration. Let's move back to funny things.

The GitHub API provides a handy endpoint (/user) to retrieve the profile of the authenticated user. This endpoint uses OAuth authentication, so it looks like a good use case.

Let's add a new method to our application to do that:

export default class App extends React.Component {  // ...  /**   * The fetchProfile method retrieves the authenticated   * user profile on GitHub (the request is proxied through Pizzly)   */  fetchProfile(authId) {    console.log("Fetching profile...");    this.github      .auth(authId)      .get("/user")      .then((response) => response.json())      .then((json) => {        console.log("Successfully fetched profile!", json);        this.setState({ profile: json });      })      .catch(console.error);  }  // ...}

And voil!

NB: To authenticate the request, we have provided an authId. It's like a user identity for that particular API. It was generated (and saved) with the connect() method.

What's next?

You now know how to authenticate a user towards any OAuth based API using React.

It's easily adaptable to all the most famous APIs. No need to create backend routes or understand every single concept of OAuth. Pizzly takes care of that for you (and for the experts, Pizzly automatically refreshes the access_token).

Again, have a look at the CodeSandbox to have a full understanding of the code and share your thoughts/questions in the comments below


Original Link: https://dev.to/frenchcooc/how-to-make-api-calls-in-react-g1e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To