From Your First Free API Call to Advacned Options & Keys Safety.

If you've spent any time building websites, you've probably heard the term "API" thrown around constantly. APIs power almost everything interesting on the modern web from the weather widget on your homepage, the map on your contact page, to the payment form in your checkout. In this guide, we'll start from zero: what an API actually is, how to make your very first API call with no signup required, and then how to level up to more powerful APIs that require keys. We'll even discuss how to keep those keys secure so you don't wake up to a surprise bill.
LINK TO FULL CODE AND LIVE EXAMPLES
What Is an API, Anyway?
API stands for Application Programming Interface. That's a mouthful, so here's the classic analogy: an API is like a waiter in a restaurant.
You (the customer) don't walk into the kitchen and cook your own meal. Instead, you look at a menu of what's available, tell the waiter what you want, and the waiter brings it back to you. You don't need to know how the kitchen works. You just need to know how to order.
An API works the same way:
- The menu is the API's documentation. It is a list of what you can ask for and how to ask for it.
- Your order is a request. Usually an HTTP request to a specific URL (called an endpoint).
- The dish is the response. Usually data in JSON format that your website can display.
When your website asks a weather service "what's the temperature in Philadelphia?", it's not scraping a weather website or running its own forecasting models. It's sending a structured request to an endpoint, and getting structured data back. That's it. That's an API.
Most web APIs you'll use are REST APIs, which just means you interact with them using ordinary web URLs and HTTP methods like GET (fetch data) and POST (send data). If you can type a URL into a browser, you already have most of the mental model you need.
Your First API Call: A Weather Widget with No Login Required
The best way to understand APIs is to call one, and the best APIs to start with are the ones that require no account, no API key, and no credit card. You can literally paste the URL into your browser and see the data.
Open-Meteo is a fantastic example — a free weather API with no key required for non-commercial use. Here's a request for the current temperature in Philadelphia:
Paste that into your browser and you'll get back JSON that looks something like this:
{
"latitude": 40.0,
"longitude": -75.5,
"current_weather": {
"temperature": 27.3,
"windspeed": 11.2,
"weathercode": 1,
"time": "2026-07-11T14:00"
}
}
Congratulations — you just made an API call. Now let's put it on a website. Here's a complete, working weather widget in plain HTML and JavaScript. You can use the link below to download the file or simply copy and paste the code below. But it into an HTML editor and run the file in your web browser.
<!DOCTYPE html>
<html>
<head>
<title>Simple Weather Widget</title>
</head>
<body>
<h2>Current Weather</h2>
<p id="weather">Loading...</p>
<script>
const url = "https://api.open-meteo.com/v1/forecast?latitude=40.0&longitude=-75.5¤t_weather=true";
fetch(url)
.then(response => response.json())
.then(data => {
const w = data.current_weather;
document.getElementById("weather").textContent =
`Temperature: ${w.temperature}°C · Wind: ${w.windspeed} km/h`;
})
.catch(error => {
document.getElementById("weather").textContent = "Couldn't load weather data.";
console.error(error);
});
</script>
</body>
</html>
Three things are happening here:
fetch(url)sends a GET request to the API endpoint.response.json()converts the raw response into a JavaScript object.- We pull out the fields we want and drop them into the page.
That pattern of fetch, parse & display is the backbone of nearly every API integration you'll ever write. Everything else is variations on the theme.
Top No-Login APIs to Practice With
Once you've got the weather widget working, here are some other excellent APIs that require no key or signup. They're perfect for practice projects, portfolio pieces, and teaching:
| API | What It Does | Example Use |
|---|---|---|
| Open-Meteo | Weather forecasts and historical data | Weather widgets, dashboards |
| REST Countries | Data on every country — flags, populations, currencies | Country picker, geography quiz |
| PokéAPI | Every Pokémon, move, and ability ever | Fun front-end practice projects |
| JSONPlaceholder | Fake posts, users, and comments for testing | Prototyping before your real backend exists |
| Frankfurter | Currency exchange rates | Currency converter |
| Nager.Date | Public holidays for 100+ countries | Holiday calendars, scheduling tools |
| Free Dictionary API | Definitions, phonetics, synonyms | Word-of-the-day widget |
| Art Institute of Chicago API | Over 100,000 artworks with images | Art gallery or slideshow project |
| SpaceX API | Launches, rockets, capsules | Launch countdown tracker |
A quick tip: because these are free and unauthenticated, they sometimes change or disappear, and they usually have informal rate limits. They're ideal for learning and hobby projects, but for anything commercial you'll eventually graduate to the next tier.
Leveling Up: APIs That Require Keys
Most professional-grade APIs such as Google Maps, OpenWeatherMap's paid tiers, Stripe, OpenAI, Anthropic & Twilio all require an API key. A key is a long string of characters, something like:
sk_live_51Hx9f2KJh3gT7...
You get one by creating an account with the provider, and you include it with every request, either in the URL or (more commonly and more properly) in a request header:
Authorization: Bearer YOUR_API_KEY
Why do these providers bother with keys? Three main reasons:
- Identification — the key tells the provider who is making the request.
- Rate limiting — providers can cap how many requests you make per minute or per day.
- Billing — many keyed APIs charge per request, per token, or per thousand calls.
For our working examples, we'll use OpenWeatherMap. This is the most popular keyed weather API and a great first "real" API. Sign up for a free account, verify your email, and you'll find your API key on your account page. The free tier is generous (60 calls per minute, one million calls per month on the classic endpoints) and doesn't require a credit card. One gotcha worth knowing up front: a brand-new key can take a couple of hours to activate, so if your first requests return a 401 Unauthorized, wait a bit before assuming your code is broken.
The endpoint we'll call is the classic Current Weather API:
https://api.openweathermap.org/data/2.5/weather?q=Philadelphia&units=metric&appid=YOUR_API_KEY
It returns JSON with the temperature in main.temp, a text description in weather[0].description, humidity in main.humidity, and plenty more.
Why API Key Security Really Matters
If you weren't required to enter a credit card, a leaked key isn't the end of the world but it can still cause you headaches. Someone could burn through your entire quota (suddenly your weather widget stops working because a stranger used up your million free calls), and if they use your key for abuse or spam, it's your account that gets rate-limited, suspended, or banned from the service entirely. Getting un-banned when the abuse "came from your key" is not a fun support ticket to file. However, if you did put a credit card on file, the stakes jump considerably: your API key is essentially a credit card number for that service. Anyone who has it can make requests as you, and you pay the bill. On pay-as-you-go services, there's often no hard ceiling unless you set one yourself, which is how developers end up with four-figure surprise invoices from a key that leaked overnight.
This isn't a theoretical risk. There are automated bots that do nothing but scan public GitHub repositories, pastebins, and website source code looking for exposed keys. Developers have accidentally committed a cloud API key to a public repo and racked up thousands of dollars in charges within hours, because bots found the key and used it to spin up crypto-mining servers or hammer paid endpoints. Some providers (like AWS and OpenAI) now scan GitHub themselves and auto-revoke leaked keys. That's how common this problem is.
The single most common mistake beginners make is this one:
<!-- ❌ NEVER DO THIS -->
<script>
const API_KEY = "sk_live_51Hx9f2KJh3gT7abc123";
fetch(`https://api.example.com/data?key=${API_KEY}`);
</script>
Anything in your front-end JavaScript is public. Every visitor can open their browser's developer tools, click "View Source," and read your key in plain text. It doesn't matter how obscure the variable name is or whether you minify the code. If the browser can see it, everyone can see it.
The golden rule: keyed API calls belong on your server, not in the browser. Your front end talks to your server, and your server (which holds the key privately) talks to the API. This pattern is called a proxy or backend-for-frontend, and it looks like this:
Browser → Your server (key lives here) → Third-party API
Let's look at how to do this properly in three popular languages.
Securing API Keys in PHP
PHP is still the workhorse of a huge share of the web (including every WordPress site), and it's easy to handle keys safely.
Step 1: Store the key in an environment variable, not in your code. The most common approach is a .env file in your project root:
# .env
OPENWEATHER_API_KEY=your_actual_key_here
Step 2: Make sure .env is never uploaded or committed.
Add it to your .gitignore which is a plain text file in your project folder where you list anything Git should never save or upload (there's more on this in the checklist at the end). You also need to make sure visitors can't simply open the file in their browser. Your "web root" is the folder your hosting server shares with the public. It's often named public_html, www, or htdocs and anything inside it can potentially be reached by typing a URL. If your .env file lives in there, someone could try visiting yoursite.com/.env and read your key in plain text. On Apache servers you can block that with two lines in your .htaccess file:
<Files .env>
Require all denied
</Files>
Better yet, move the .env file up one level, outside the web root entirely. If it's not in the public folder, no URL can ever reach it. The simplest security is a file the internet can't see.
Step 3: Load it and use it server-side. Using the popular vlucas/phpdotenv package (composer require vlucas/phpdotenv):
If you have never done this read over the docs on your server or check out this article.
<?php
// weather-proxy.php
require __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$apiKey = $_ENV['OPENWEATHER_API_KEY'];
$city = urlencode($_GET['city'] ?? 'Philadelphia');
$url = "https://api.openweathermap.org/data/2.5/weather?q={$city}&units=metric&appid={$apiKey}";
$response = file_get_contents($url);
if ($response === false) {
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Weather service unavailable']);
exit;
}
$data = json_decode($response, true);
// Return only the fields the front end needs — never echo the raw
// request URL or anything containing your key
header('Content-Type: application/json');
echo json_encode([
'city' => $data['name'],
'temp' => $data['main']['temp'],
'description' => $data['weather'][0]['description'],
'humidity' => $data['main']['humidity'],
]);
Your front-end JavaScript now calls your endpoint instead of the API directly:
fetch('/weather-proxy.php?city=Philadelphia')
.then(res => res.json())
.then(data => {
console.log(`${data.city}: ${data.temp}°C, ${data.description}`);
});
The key never leaves your server. A visitor viewing your page source sees only /weather-proxy.php This is completely useless to them without your server's .env file.
On shared hosting without Composer, you can also set environment variables in your hosting control panel or in an Apache config, then read them with getenv('OPENWEATHER_API_KEY'). The principle is the same: the key lives in the server environment, never in a file that gets committed or served.
Securing API Keys in Node.js
Node.js makes the proxy pattern especially natural, since your backend is already JavaScript. The standard tool here is the dotenv package.
Step 1: Create your .env file (and add it to .gitignore immediately. You should do this before your first commit, not after):
# .env
OPENWEATHER_API_KEY=your_actual_key_here
Step 2: Build a small Express proxy (npm install express dotenv):
// server.js
require('dotenv').config();
const express = require('express');
const app = express();
app.get('/api/weather', async (req, res) => {
const city = encodeURIComponent(req.query.city || 'Philadelphia');
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${process.env.OPENWEATHER_API_KEY}`;
try {
const response = await fetch(url);
if (!response.ok) {
return res.status(response.status).json({ error: 'City not found or service error' });
}
const data = await response.json();
// Return only what the front end needs
res.json({
city: data.name,
temp: data.main.temp,
description: data.weather[0].description,
humidity: data.main.humidity
});
} catch