Getting started overview

Integrating with the Storm Glass API involves a standard process: account creation, API key retrieval, and making authenticated HTTP requests. The service provides marine weather data, including forecasts and historical information, for global locations. Developers can access parameters such as wave height, wind speed, and swell direction, which are relevant for various marine applications. Storm Glass offers a free Developer Plan that includes 50,000 requests per month, allowing for initial development and testing without immediate cost Storm Glass pricing page.

The API supports both HTTP GET requests for data retrieval and provides official SDKs for Python and Node.js to simplify integration. Data is returned in JSON format, which is a common standard for web APIs due to its human readability and ease of parsing by machines JSON data interchange format overview. Understanding the available parameters and coordinate system is essential for accurate data requests. For detailed information on specific endpoints and parameters, refer to the Storm Glass API documentation.

Here's a quick reference table outlining the initial steps:

Step What to Do Where
1. Sign Up Create a free Storm Glass account. Storm Glass Pricing Page (select Developer Plan)
2. Get API Key Locate your unique API key in your account dashboard. Storm Glass Account Dashboard (after signup)
3. Construct Request Formulate an HTTP GET request with desired parameters and coordinates. API Documentation / Code Editor
4. Authenticate Include your API key in the Authorization header of your request. HTTP Request Header
5. Execute & Parse Send the request and process the JSON response. Code Editor / Terminal (e.g., cURL)

Create an account and get keys

To begin using the Storm Glass API, you must first create an account. This process typically involves navigating to the Storm Glass website and selecting a plan, often starting with the free Developer Plan designed for evaluation and low-volume usage. On the Storm Glass pricing page, locate the Developer Plan and proceed with the signup process. This will require providing an email address and creating a password.

Upon successful account creation and verification (if required), you will gain access to your Storm Glass user dashboard. Within this dashboard, your unique API key will be displayed. The API key is a crucial credential for authenticating your requests to the Storm Glass API. It acts as a token that identifies your application and authorizes it to access data based on your subscription plan. It is important to treat your API key as sensitive information, similar to a password. Do not embed it directly into client-side code that could be publicly exposed, and restrict its use to server-side environments or secure proxies when possible.

The API key is typically a long string of alphanumeric characters. For example, it might look like abcdef12-3456-7890-abcd-ef0123456789. This key will need to be included in the Authorization header of every API request you make. The format for this header is usually Authorization: API_KEY, where API_KEY is your retrieved key. Secure management of API keys is a standard practice in API integration, helping prevent unauthorized access to your account and usage limits Google Maps API key security recommendations.

Your first request

After obtaining your API key, you can make your first API call. This example demonstrates fetching wave height data for a specific location using a simple HTTP GET request. We will use cURL for brevity, but the same principles apply to using an SDK or any HTTP client library.

The Storm Glass API requires geographic coordinates (latitude and longitude) and specifies which parameters you wish to retrieve. For this example, we'll request wave height (waveHeight) for a point near San Francisco, California.

API Endpoint Structure

The primary endpoint for marine weather forecasts is https://api.stormglass.io/v2/weather/point. This endpoint accepts query parameters for latitude, longitude, and a comma-separated list of weather parameters.

Example Request Parameters:

  • lat: 37.89
  • lng: -122.5
  • params: waveHeight
  • start: Current Unix timestamp (e.g., 1678886400 for March 15, 2023, 00:00:00 UTC)
  • end: Current Unix timestamp + 1 hour (e.g., 1678890000 for March 15, 2023, 01:00:00 UTC)

Note: For start and end parameters, it is recommended to use Unix timestamps. Many programming languages offer functions to convert dates to Unix timestamps. If these parameters are omitted, the API will return forecast data for the next 7 days in 3-hour intervals, starting from the current time. When making your actual request, ensure you use current or relevant timestamps for start and end.

Constructing the cURL Command

Replace YOUR_API_KEY with the actual API key you obtained from your Storm Glass dashboard. You will also need to generate current Unix timestamps for start and end. For instance, in Python, you can get a Unix timestamp with import time; int(time.time()).

curl -X GET \
  'https://api.stormglass.io/v2/weather/point?lat=37.89&lng=-122.5&params=waveHeight&start=1678886400&end=1678890000' \
  -H 'Authorization: YOUR_API_KEY'

Expected JSON Response (partial)

A successful response will return a JSON object containing the requested data. The hours array will contain objects for each requested time point, with the specified parameters and their values.

{
  "hours": [
    {
      "time": "2023-03-15T00:00:00+00:00",
      "waveHeight": [
        {
          "value": 1.2,
          "source": "noaa"
        }
      ]
    },
    {
      "time": "2023-03-15T01:00:00+00:00",
      "waveHeight": [
        {
          "value": 1.1,
          "source": "noaa"
        }
      ]
    }
  ],
  "meta": {
    "lat": 37.89,
    "lng": -122.5,
    "params": [
      "waveHeight"
    ],
    "start": "2023-03-15T00:00:00+00:00",
    "end": "2023-03-15T01:00:00+00:00",
    "data_points": 2
  }
}

The value field within waveHeight represents the wave height in meters. The source indicates the model used to generate the forecast, such as NOAA's operational models.

Using an SDK (Python Example)

For Python developers, the official SDK simplifies API interactions. First, install the SDK:

pip install stormglass

Then, you can make a request:

import os
import requests
from datetime import datetime, timedelta, timezone

api_key = os.environ.get("STORMGLASS_API_KEY") # It's best practice to get key from env variables

if not api_key:
    print("Error: STORMGLASS_API_KEY environment variable not set.")
    exit(1)

lat = 37.89
lng = -122.5
params = 'waveHeight'

# Get current time and 1 hour later in UTC Unix timestamps
now_utc = datetime.now(timezone.utc)
start_timestamp = int(now_utc.timestamp())
end_timestamp = int((now_utc + timedelta(hours=1)).timestamp())

headers = {
    'Authorization': api_key
}

request_url = (
    f'https://api.stormglass.io/v2/weather/point?'
    f'lat={lat}&lng={lng}¶ms={params}&start={start_timestamp}&end={end_timestamp}'
)

try:
    response = requests.get(request_url, headers=headers)
    response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
    data = response.json()
    print("API Response:")
    print(data)
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err} - {err.response.text}")
except requests.exceptions.ConnectionError as err:
    print(f"Connection error occurred: {err}")
except requests.exceptions.Timeout as err:
    print(f"Timeout error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"An unexpected error occurred: {err}")

This Python example demonstrates setting the API key as an environment variable (recommended for security), constructing the URL with dynamic timestamps, and handling potential HTTP errors. The requests library is a popular choice for making HTTP requests in Python due to its ease of use Python Requests library documentation.

Common next steps

Once you have successfully executed your first request to the Storm Glass API, several common next steps can help you further integrate and utilize its capabilities:

  1. Explore More Parameters: The Storm Glass API offers a wide range of marine weather parameters beyond just wave height, including wind speed, swell direction, air temperature, and precipitation. Consult the Storm Glass API documentation to identify other parameters relevant to your application and integrate them into your requests.
  2. Implement Error Handling: Robust applications require proper error handling. The API returns standard HTTP status codes (e.g., 400 for bad request, 401 for unauthorized, 429 for rate limit exceeded, 500 for server errors). Implement logic in your code to catch these errors and provide appropriate feedback or retry mechanisms.
  3. Manage Rate Limits: The free Developer Plan has a limit of 50,000 requests per month. Paid plans offer higher limits. Monitor your API usage, and if necessary, implement caching strategies or consider upgrading your plan to accommodate increased demand Storm Glass pricing details.
  4. Utilize SDKs and Libraries: While direct HTTP requests are feasible, using the official Python or Node.js SDKs, or general-purpose HTTP client libraries (like axios for JavaScript or requests for Python), can streamline development, particularly for handling authentication, request construction, and response parsing.
  5. Integrate Real-time Data: The API provides both forecast and historical data. Determine whether your application requires near real-time updates or can utilize less frequent batch requests. Set appropriate polling intervals based on your needs and the API's rate limits.
  6. Visualize Data: For applications displaying weather information, integrate mapping libraries (e.g., Google Maps Platform, Mapbox) or charting libraries (e.g., Chart.js, D3.js) to visualize the retrieved data effectively.
  7. Secure API Key: Reinforce practices for securing your API key. Avoid hardcoding it into your application code. Use environment variables, a secure configuration management system, or a secrets manager, especially when deploying to production environments.

Troubleshooting the first call

When making your initial API call to Storm Glass, you might encounter issues. Here are common problems and their solutions:

  1. 401 Unauthorized Error:

    • Symptom: The API returns an HTTP 401 status code, often with a message like "Unauthorized."
    • Cause: This usually means your API key is missing, incorrect, or improperly formatted in the Authorization header.
    • Solution:
      • Double-check that you have included the Authorization header with your correct API key.
      • Ensure there are no typos or extra spaces in your API key.
      • Verify that the header format is Authorization: YOUR_API_KEY (without the word 'Bearer' or other prefixes unless specified by Storm Glass documentation).
      • Confirm your API key is still active in your Storm Glass account dashboard.
  2. 400 Bad Request Error:

    • Symptom: The API returns an HTTP 400 status code, often with a message indicating invalid parameters.
    • Cause: This typically occurs when required parameters are missing, malformed, or their values are out of expected ranges.
    • Solution:
      • Verify that lat, lng, and params are all present in your request URL.
      • Check that latitude and longitude values are within valid ranges (e.g., latitude between -90 and 90, longitude between -180 and 180).
      • Ensure the params list contains valid parameter names as listed in the Storm Glass documentation.
      • If using start and end, ensure they are valid Unix timestamps and that start is not after end.
      • Check for URL encoding issues if your parameters contain special characters (though less common for lat/lng/params).
  3. 429 Too Many Requests Error:

    • Symptom: The API returns an HTTP 429 status code.
    • Cause: You have exceeded your plan's rate limit for a given time period (e.g., too many requests per minute or per month).
    • Solution:
      • Wait for the rate limit period to reset before making further requests.
      • Review your application's request frequency and implement client-side rate limiting or caching to reduce API calls.
      • Consider upgrading your Storm Glass plan if your legitimate usage consistently hits the free tier's limits Storm Glass pricing options.
  4. Connection Errors (e.g., DNS resolution failure, network timeout):

    • Symptom: Your HTTP client reports that it cannot connect to the host or the request times out.
    • Cause: Issues with your internet connection, DNS configuration, or a temporary problem with the Storm Glass server.
    • Solution:
      • Verify your internet connection.
      • Check if api.stormglass.io is reachable using a simple ping or curl command from your terminal.
      • Temporarily disable any VPNs or firewalls that might be interfering with network requests.
      • If the problem persists, check the Storm Glass status page (if available) for known outages.
  5. Incorrect or Unexpected Data in Response:

    • Symptom: The JSON response is not structured as expected, or the data values seem incorrect.
    • Cause: Misunderstanding of parameters, incorrect coordinate usage, or an issue with how the response is being parsed.
    • Solution:
      • Carefully review the Storm Glass API documentation for the specific endpoint and parameters you are using.
      • Ensure the latitude and longitude accurately represent your desired location.
      • Verify your JSON parsing logic correctly extracts data from the hours array and the specific parameter objects.
      • Check the source array in the meta field of the response to understand which data models are contributing to the forecast.