This is an excerpt from my APIs with Vanilla JS pocket guide.
To authenticate you, the API may require:
- Your username and password.
- A key and secret.
- An API key or OAuth token.
These are often passed to the API as query string values on the endpoint URL. For example, here’s how you make a call to the New York Times API.
Anyone who knows how to view source or view requests in their browser’s Developer Tools can view those credentials, steal them, and use them to access the API as you.
For APIs that let you send new data or update and delete existing data, that can be really dangerous. It’s also an issue for APIs that expose private data, restrict the number of calls you can make, or cost money to use.
The only time I personally would make an exception to that are for APIs that are:
- Free, and
- Only allow
- Surface public data that’s accessible elsewhere.
Bonus points of the credentials are restricted in use to a specific domain or URL.
This middleware API stores your credentials securely on the server, and makes the real API call on your request. It then sends back the data, optionally filtering out any data you don’t want exposed publicly first.
An example: the Mailchimp API
For example, the Mailchimp API requires an API key and private list ID to subscribe users.
I don’t want to expose either of those publicly, or someone could spam subscribe my list, delete subscribers, and so on.
In WordPress, I can save my API key and list ID. I can also add a list of allowed domains, and any requests that come from domains other than those are ignored.
On the server, it uses the
wp_remote_request() method and the arguments I send along to ping the actual Mailchimp API or subscribe a new user (or update an existing one). Then, it returns a status code letting me know if it worked or not.
How can you do something like that?
There are countless ways to set up your own server-side middleware for your APIs, and getting into the details is well beyond the scope of this guide.
So much of what I would recommend depends on your comfort writing server-side code, the programming languages you already know, and what you’re trying to accomplish.
Because my background is in WordPress, and because it provides some create helper methods for creating middleware endpoints and making Ajax calls in PHP, it’s my go-to solution for this kind of thing.
The best solution for you might be something different.