Request-Response

The Full-Stack Blog

How to Use API Keys

February 06, 2024
Disponible en español

Server-side APIs allow developers to access data made available by third-party companies and organizations. To use this data, developers can create applications that make requests to URLs, or endpoints, provided by those third-party organizationsand in turn, the endpoints respond with the requested data.

Some APIs allow developers to request data without any credentials; others require an API key, to prevent users from making too many requests, potentially disrupting a website's ability to function.

In time, you'll learn how to create these requests on the back end of your application, to avoid exposing your key to other users. But for the purposes of this guide, you'll include an API key in a URL that you'll use in your JavaScript code on the front end.

Note There are multiple ways to make API requests. This guide teaches just one approach, using the OpenWeather API for demonstration.

Request an API Key

Before you start working with the OpenWeather API, you'll need to request an API key. To do that, visit the OpenWeather signup page and create an account.

After you've created your account, if you are redirected to a page with several secondary headings (such as New Products, Services, and API Keys), click on API Keys.

If you aren't redirected to that page, click on your username in the upper right-hand corner of the window, to display a drop-down menu. From this menu, select My API Keys.

You'll receive a message that you can generate as many API keys as necessary for your subscription. In this case, though, you'll only need to generate one key.

Under Create Key, give your API key a name that's unique to your project, then click the Generate button. This will take you to a page that lists any keys that you've created. They should look like a random string of 32 characters. Copy the new key that you've created, and save it in the JavaScript file where you'll be making API calls.

Create a Variable to Store the API Key

Now that you've created an API key, you'll want to store it in a variable so that you can reuse it in your code without having to type it repeatedly.

The variable will resemble the following code snippet:

const APIKey = "12341234123412341234123412341234";

Note that the name of the variable is APIKey. You can name your variable something similar. It should be meaningful and clear so that another developer can understand its purpose.

Note: The string in the preceding code isn't an actual API key but rather an example of a 32-character string. The characters in your API key will be random and non-repeating.

Create Variables for the API Call

Depending on the API call that you'll make, you might want to include different query parameters. This will often require your application to accept user input, so you'll want to create variables that can hold this input after the user has submitted it.

In this example, we'll create an API call using the Current Weather Data portion of the OpenWeather API, and we'll search by city name. According to the OpenWeather documentation on calling current weather data for one location, you can make an API call using just the city name or by using a combination of the city name, state code, and country code.

Note: Searching by state codes is only available for locations in the United States.

For this example, we'll collect user input for just the city name and store it in a variable, as shown in the following code:

let city;

You'll want to allow your application to accept user input and store it in the variable that you've created. You'll also likely need to specify state and country variables in your API call, as multiple countries or states might have cities with the same name. For the purposes of this guide, you can use the city variable that you just created.

Construct a Query URL to Make the API Call

Now that you've created variables to store your API key and the user input for the city, you can construct a query URL, which you'll use to make the API call.

You might have noticed that the OpenWeather API provides several URLs, each of which you can use to get different information. For this example, you'll use the URL associated with Current Weather Data. To use other data points from the API, you'll need to use the URL listed in that section of the documentation.

The OpenWeather Current Weather Data documentation provides an example of how to make an API call using just the city name, as shown in the following code:

api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

This is exactly what we're looking for! We've already created variables for the API key and the city, so we just need to replace the relevant placeholders in the URL with those variables.

But first, look at the Parameters section of the documentation, which you'll find after the API Call section. Parameters are the variable search terms that you can add to an API call to specify the data you want to request.

This section lists a number of parameters, but only the following two are required:

  • q: The query parameter, where we'll add the city variable.

  • appid: The application id or key, where we'll add the API key variable.

Note: For the purposes of this guide, we will focus on these two required parameters. Feel free to seek out more information about the optional parameters!

Great! Now that we know how OpenWeather's query URL works, let's construct one using the variables that we created earlier. We'll use string concatenation to create a new variable called queryURL, which will store the OpenWeather Current Weather Data URL and the necessary variables, as shown in the following code:

const queryURL = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;

Let's look more closely at the different parts of this variable that we just created:

  • http://api.openweathermap.org/data/2.5/weather is the base URL for calling the Current Weather Data API.

  • The question mark (?) marks the boundary between the base URL of the API call and the query terms of the API call.

  • As we mentioned earlier, q= is the query parameter, where we can add any user input to specify the data that we want to request in the API call. The value assigned to this parameter is called the query string.

  • Following the query parameter, we concatenate the user input, which is stored in the variable city. This is the query string assigned to the query parameter.

  • The ampersand character (&) indicates that we're adding another parameter after the query parameter.

  • Next, we concatenate the other required parameter, appid=, where we'll add the API key specific to the application.

  • Finally, we concatenate the APIKey variable that contains the key we obtained at the beginning of this guide.

Now that you have constructed a variable to hold your query URL, you can implement it in an API call using the Fetch API!

Make the API Call Using Fetch

The Fetch API is a Web API built into the browser that allows you to make server-side API calls without having to use AJAX and install a bulky library like jQuery.

Now that you have created your query URL, you only need to call the Fetch API to pass the query URL in as a parameter, as shown in the following example:

fetch(queryURL)

Remember that the query URL won't work automatically as it's written. You'll need to adjust your application to accept user input, to store in the city variable that you've created.

Use the Response Data in Your Website

What's next? Once we have the application working, we can use the response data that's returned by the query in the application. We won't tackle that now, but it would function the same way as an API that doesn't require an API key.

Remember, you can make API calls in other ways too. As you learn more, you'll discover better ways to protect your API keys and to make API calls on the back end. But for now you have an easy guide to help you get started!

This page was updated 2 months ago
© 2022 edX Boot Camps LLC. Confidential and Proprietary. All Rights Reserved.

Category: apis

Tagged under: apis, guide,

All Posts