When we build websites and webapps that leverage the benefits of being delivered on the CDN (benefits include security, performance, infinite scaling, no backend infrastructure required) we will often run into limitations when we want more powerful, dynamic functionality. The best way to increase functionality is through the integration of APIs. APIs give our frontends near infinite possibilities; i.e. we can easily connect contact forms, process outside data, store information, or present information like the weather forecast, flight schedules, currency exchange rates etc. One of the key benefits of having our frontend on the CDN is not having to deal with building and maintaining backend infrastructure, but how do we integrate APIs securely and easily without a backend? Where do we secure the private API keys? What if we don't want user authentication prior to allowing our users to interact with a 3rd party API? We will go through the simplest way of connecting APIs with automated security using KOR Connect.
How quickly can this be done and what happens?
The answer is in a few quick minutes if the API you are integrating with has decent documentation, but why would you want to integrate with an API that doesn't anyways? KOR Connect does everything on the backend, and as the user we only have to copy-paste the KOR Connect public endpoint and the header into our code after entering the integrating API information into KOR Connect. Everything else is done on KOR Connect's end.
Here are some of the things that happen automatically on KOR Connects end after you make a connection; bot controls are activated that inspect for, miscellaneous bots, security related bots, calls coming from automated browsers, black listed origins, and user agents that don’t seem to be coming from a browser; these calls are blocked if they don’t pass inspection. Furthermore KOR Connect validates the access-control-allow-origin header from your allowed origins, and provides a per user rate limiter that can block malicious actors abusing calls without causing any interruptions to other users.
Now let’s walk through an example integrating 2 APIs into our frontend; a geolocation API and the Open Weather API.
KOR Connect Backendless Reactjs Application
We will be giving our ReactJS frontend the ability to allow users to enter any address and get the current weather conditions alongside other details such as the wind speed, humidity and temperature. The challenge is that we are going to be using two APIs; one to translate the address into latitude and longitude, and another API to give us the weather conditions for that location. We are providing this multi API integration as an example to show that you can integrate as many APIs as you would like into a single project. You can also quickly and easily integrate just one API as well, by following along.
This web app can be hosted on any CDN or static site service like S3, Gitlab pages, Netlify, etc.
The APIs
Head over to Rapid API and subscribe to Forward & Reverse Geocoding as well as the Open Weather Map. After subscribing you'll be able to see your API Key in the Code Snippets section of each API's endpoint tab. Save that API key as well as the URL.
KOR Connect
If you already have a KOR Connect account you can sign in or you can create a new account.
Now from the KOR Connect dashboard select the Connect API button and fill in the form for a new connection. The only fields you need to change from the following image are the API Key and the allowed domain (choose the domain you'll be hosting your app from). The API key is the one you stored in the previous step. Optionally you can add more domains and change the name of the connection.
Repeat the process for the Weather API connection, see the following image for more details.
With your connections created you are now able to enter each connection via View Details to retrieve each secure URL and header that you'll need to include in your code.
You can modify the per user rate limit for your API calls at the top left of the screen. The Default is 5 calls per second. This rate limiter controls the number of calls per second, per user; so if a malicious user is attempting to increase your costs or crash your API connection that user will be blocked without causing any interference with other users. More information regarding the rate limiter here.
The Secure URL that is generated acts similar to the API base URL, and the header is using a KOR Connect generated public API key, with these two ready, you are now able to test and use your connection. Notice the Connection Mode on the top right, you are currently on Testing which means you can access KOR Connect through localhost but once you switch to production this is blocked, read more about it in the Testing and Production Modes documentation.
There is no configuration, library or import required to use KOR Connect's Single URI feature so we can jump straight to the API calls.
Here's the geolocation Axios request example where you can replace < SECURE-URL > with your secure base URL generated by KOR Connect and add the parameters you would like to have. Furthermore you can replace < PUBLIC-API-KEY > with the KOR Connect provided public API key. Here is our code you can take a look at:
const fwdGeoLocation = (loc) => {
let location = [];
let options = {
method: 'GET',
url:<SECURE-URL>,
params: {q: loc, 'accept-language': 'en', polygon_threshold: '0.0'},
headers: {
'x-api-key': '<PUBLIC-API-KEY>'
}
};
axios.request(options).then(function (response) {
location = [response.data[0].lat, response.data[0].lon];
getWeather(location[0], location[1])
}).catch(function (error) {
console.error(error);
});
}
Here is the weather API Axios request example, following the same format as above.
const getWeather = (lat, lon) => {
let options = {
method: 'GET',
url: '<SECURE-URL>',
params: {lon: lon, lat: lat},
headers: {
'x-api-key': '<PUBLIC-API-KEY>'
}
};
axios.request(options).then(function (response) {
setWeather(response.data.data[0]);
}).catch(function (error) {
console.error(error);
});
}
When the Geolocation API responds successful, it stores the result in state triggering React to render the weather information that is received. If you are interested in reviewing this implementation refer to this section of the code.
Done! You should now have your API Keys secured and integration working.
Note: One thing that you might have noticed is that we're posting the URL and API key for the world to see but this is one of the advantages of KOR Connect. The KOR Connect generated API Keys are public keys and not the Open Weather or Geolocation API Keys, and the same holds true for the URL, both values are delivered by KOR to secure and obscure the actual information you want to protect. For maintainability of your code, you might want to store KOR Connect's API key and secure URL into a .env file or as env variables depending on where you're hosting it.
Conclusion
Using KOR Connect saves a considerable amount of resources, both time and money. For an approach requiring a server, you would need to provision the infra, harden the server, add observability, keep it up to date and so on. It’s a real pain in the neck but it’s not the only option. The serverless approach is a smoother alternative, less expensive if the functions are not constantly active and easier to manage, the caveats are having to learn the vendor's serverless implementation and maintaining the runtime. With KOR Connect you can release your application once your front end is ready to go.
Top comments (1)
Hey I just tried the new Single URL Connection and it is actually so quick and simple to use! It's great, this is going to save me a lot of time in the future!