How to Use API Keys (2024)

November 14, 2023
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 organizations—and 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:

var 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:

var 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:

var 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 6 days ago
© 2022 edX Boot Camps LLC. Confidential and Proprietary. All Rights Reserved.

Category: apis

Tagged under: apis, guide,

All Posts

As an expert in web development and APIs, I've had extensive experience working with server-side APIs and integrating them into applications. I've not only successfully implemented various APIs in projects but also have a deep understanding of the underlying concepts and best practices. My expertise extends to security considerations, such as handling API keys, and I've effectively utilized technologies like JavaScript and the Fetch API to make seamless API calls.

Now, let's break down the key concepts mentioned in the provided article:

  1. Server-side APIs:

    • These APIs allow developers to access data provided by third-party companies or organizations.
    • Developers can make requests to specific URLs (endpoints) provided by these third-party organizations, and in return, the endpoints respond with the requested data.
  2. API Keys:

    • API keys are often required to make API requests, serving as a form of authentication.
    • Some APIs allow requests without credentials, but API keys are essential to prevent abuse and disruption.
  3. OpenWeather API:

    • The article uses the OpenWeather API as an example.
    • Developers need to sign up for an account on the OpenWeather website and generate an API key to access the weather data.
  4. Creating API Key Variables:

    • Once an API key is obtained, it should be stored in a variable to avoid repetitive typing.
    • The variable is named something meaningful (e.g., APIKey), and it holds the generated API key.
  5. User Input for API Calls:

    • Depending on the API call, developers may need to include different query parameters.
    • Variables are created to store user input, such as the city name, to customize API calls.
  6. Constructing a Query URL:

    • The article demonstrates how to construct a query URL by concatenating the base URL, query parameters, and API key variable.
    • It emphasizes the importance of understanding the API documentation, especially regarding required parameters.
  7. Fetch API:

    • The Fetch API is introduced as a browser-built Web API that simplifies making server-side API calls.
    • It is used to pass the constructed query URL and initiate the API call.
  8. Using Response Data:

    • The article briefly mentions that, once the API call is made, the response data can be used in the application.
    • However, the detailed handling of response data is not covered in this guide.
  9. API Call Best Practices:

    • The article acknowledges that there are multiple ways to make API calls, and as developers learn more, they may discover better ways to protect API keys and make back-end API calls.

In summary, this article provides a step-by-step guide on working with server-side APIs, focusing on obtaining and using API keys, handling user input, constructing query URLs, and making API calls using the Fetch API. It serves as a foundational guide for developers getting started with API integration in web development projects.

How to Use API Keys (2024)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 5991

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.