A Guide to Using a Third Party API with React Native
First, what the heck is a third party API?
This was one of the first questions I asked my instructors during office hours when I started at The Grace Hopper Program at Fullstack. Even before jumping into programming, I’ve heard the phrase “API” before. I knew tech giants like Facebook and Twitter had an API and that API stood for Application Programming Interface. But what did that even mean?
Third party APIs can be thought of like a toolbox a company gives to developers to use and build with. Through simple calls, APIs allow developers access to data and certain technologies. For example, using the Spotify API, I can create a website that displays my Spotify playlist and plays it right in the browser through their music player. Which is really great because I won’t need to build my own!
Like open source software, third-party APIs highlight how collaborative coding can be. Rather than build from scratch every time, a developer can find an applicable third party API and give their own applications much more functionality. In that way, to me, they are akin to NPM libraries!
If you’re new to this, before we get started, make sure you’ve chosen the right API. Do your research. Make sure you’ve found the best API for your use case. Make sure the API is well documented and well tested. Don’t be intimidated by documentation. Integrating an API that has a lot of documentation (and seemingly, a lot of steps) may take some time but the documentation will make the whole process much more simple. There are so many different APIs out there so do your research and find what works best for your own app. Check out this site to peruse some popular APIs.
Note — each API is different and may have it’s own intricacies. So, just read the documentation!
Plaid API in a Create React Native Application
For the purpose of this article, let’s look at just one API, Plaid, and how to integrate it to a Create React Native application. Plaid enables applications to connect with users’ bank accounts, (which again highlights to me how useful and easy APIs can make programming — complex and highly sensitive data like banking information becomes easily, and safely, accessible to developers through an API.) Plaid is another example of great documentation. They even have a walkthrough app to get you started.
*Our example is also a little distinct because we’re using a web API that doesn’t have support for React Native in a Create React Native application. You can still do this without ejecting your CRNA and without writing anything in Objective C or Swift, all thanks to a handy dandy npm library, react-native-plaid-link. Let’s get started!
Server-Side
- Get developer access to the API and “register” your application. You’ll then get three API keys: a
client_id
, asecret
, andpublic key
. An API key is exactly what it sounds like — a key for the developer’s app to get access to the entire API. In our example with Plaid, aclient_id
is a “non-sensitive, public identifier that is used to initialize Plaid Link”. Asecret
is a private identifier that is required for accessing any financial data. This should NEVER be in client-side code — let’s go ahead and save these three API keys in asecrets.js
file on our server-side application usingprocess.env
.
process.env.PLAID_CLIENT_ID = 'YOUR_CLIENT_ID_HERE'
process.env.PLAID_SECRET = 'YOUR_PLAID_SECRET_HERE'
process.env.PLAID_PUBLIC_KEY = 'YOUR_PLAID_PUBLIC_KEY_HERE'
2. In your routes file for all your Plaid requests, which I’ve conveniently named plaid.js
, let’s require plaid. Let’s also give our file “access” to our secrets. Plaid also gives you different environments to build in: sandbox, development, and production. When you’re building your project, always work in sandbox.
const plaid = require('plaid')const PLAID_CLIENT_ID = process.env.PLAID_CLIENT_ID
const PLAID_SECRET = process.env.PLAID_SECRET
const PLAID_PUBLIC_KEY = process.env.PLAID_PUBLIC_KEY
const PLAID_ENV = envvar.string('PLAID_ENV', 'sandbox')
3. Initialize the Plaid client. Now that we’ve initialized the Plaid client, we can access the different web endpoints and methods given to us the developers from Plaid.
const plaidClient = new plaid.Client(
PLAID_CLIENT_ID,
PLAID_SECRET,
PLAID_PUBLIC_KEY,
plaid.environments[PLAID_ENV]
);
Client-Side*
*I’ll be VERY brief in this section because it has a lot more to do with Plaid Link in a React Native app than integrating a third party API to your application. If you’re curious how it was done, be sure to check out the Capstone project (coming soon!).
4. Connect your User to Plaid using Plaid Link. In your Link Component, render the PlaidAuthenticator
, imported from react-native-plaid-link
.
render() {
return <PlaidAuthenticator
onMessage={this.onMessage}
publicKey="YOUR_PLAID_PUBLIC_KEY"
env="sandbox"
product="auth,transactions"
clientName="YourAppNameHere"
/>
}onMessage = (data) => {
this.setState({data})
}
5. Send the public token to the backend via a thunk.
export const sendToken = token => {
return async dispatch => {
try {
const res = await axios.post(`${server}/api/plaid/plaid_exchange`, { public_token: token });
dispatch(sendPublicToken(res.data));
} catch (err) {
console.log('Error sending public token: ', err.message);
}
}
}
And back to Server-Side
This part is also a bit concise because… well, now, you’re all set up to make any kind of POST
request to Plaid you want. Plaid uses POST
requests to essentially have the app “GET
” information: bank, accounts, and transactions information.
6. Write your routes and make requests to Plaid! (The code below was taken directly from the Plaid API).
app.post('/get_access_token', function(request, response, next) {
PUBLIC_TOKEN = request.body.public_token;
plaidClient.exchangePublicToken(PUBLIC_TOKEN, function(error, tokenResponse) {
if (error != null) {
console.log('Could not exchange public_token!' + '\n' + error);
return response.json({error: msg});
}
ACCESS_TOKEN = tokenResponse.access_token;
ITEM_ID = tokenResponse.item_id;
console.log('Access Token: ' + ACCESS_TOKEN);
console.log('Item ID: ' + ITEM_ID);
response.json({'error': false});
});
});
7. Use methods, like getTransactions
, given by Plaid to make even MORE requests!
plaidClient.getTransactions(accessToken, '2017-01-01', '2017-02-15',{
count: 250,
offset: 0,
}, (err, result) => {
// Handle err
const transactions = result.transactions;
});
If your API allows, you may even be able to do API calls directly from your client-side application to the API!
Data Flow between our Client-Side Application and our Server-Side Application (and our Server-Side Application and the Plaid API)
Let’s quickly run through the data flow.
A User logs in to their bank account using Plaid Link and PlaidAuthenticator, which returns a public token. Our client-side application sends that public token to our server-side application. Our server-side application converts that public token to an access token. Our server-side application now acts as a client and sends a request to the Plaid API/server for transactions based on that access token. Our server-side then receives the data and stores it in our server. Now, our client-side application can make requests for transactions directly to our server!
Wrapping Up
APIs sound complicated — but it really isn’t. If you’re a new developer starting to build their portfolio, you’ve probably already made a CRUD app. All you really need is an API key and you can make calls to the Web API endpoints rather than to your local host. Take your CRUD app to the next level by integrating some kind of API. Using APIs will really expand your world and your abilities.