Fetch API and API Key

Fetch API and API Key
0.0 0

#1

How should I send the API key when using Fetch to request data?
Thank you


#2

@cpazinatto

Good question!

There are number of ways to do this. But in my small experience working with fetch, my opinion on this is to use dotenv. If you’re not worried about making your API Keys public, you can simply just add it towards the end within your fetch method.

For example:

> app.get('/YourPath/:parameterName', function (req, res) {
>     fetch(`${https://apiUrl.org/appData}&parameterURI=${req.params.parameterName}APIKEY=123456TheCakeIsALie`)
>         .then(response => response.json())
>         .then(weather => res.send(weather))
> .catch(error => res.send(error))

You can probably clean this up by declaring a variable with the API URL and using dotenv to hide your API Key:

var apiURL = ‘https://apiurl.org/data/whatever’;

> app.get('/YourPath/:parameterName', function (req, res) {
>     fetch(`${apiURL}&parameterURI=${req.params.parameterName}?APIKEY=${process.env.API_KEY}`)
>         .then(response => response.json())
>         .then(weather => res.send(weather))
> .catch(error => res.send(error))