OpenWeatherMap Python API Docs | dltHub

Build a OpenWeatherMap-to-database pipeline in Python using dlt with AI Workbench support for Claude Code, Cursor, and Codex.

Last updated:

OpenWeatherMap is a global weather data platform exposing REST APIs for current weather, forecasts, historical data, air pollution, maps and geocoding. The REST API base URL is https://api.openweathermap.org and all requests require an API key (appid) supplied as a query parameter or header.

dlt is an open-source Python library that handles authentication, pagination, and schema evolution automatically. dlthub provides AI context files that enable code assistants to generate production-ready pipelines. Install with uv pip install "dlt[workspace]" and start loading OpenWeatherMap data in under 10 minutes.


What data can I load from OpenWeatherMap?

Here are some of the endpoints you can load from OpenWeatherMap:

ResourceEndpointMethodData selectorDescription
current_weather/data/2.5/weatherGET(object) — top-level responseCurrent weather by city name, city id, coordinates or ZIP code (returns a single object; weather details inside weather array)
forecast_5day_3hour/data/2.5/forecastGETlist5 day / 3 hour forecast (response includes list array of forecast entries)
forecast_16day_daily/data/2.5/forecast/dailyGETlist16 day daily forecast (legacy endpoint; response includes list)
one_call_3/data/3.0/onecallGETcurrent, minutely, hourly, daily, alertsOne Call 3.0 aggregated weather: current (object), hourly (array), daily (array), minutely (array), alerts (array). Use exclude param to omit sections.
geocoding_direct/geo/1.0/directGET(top-level array)Direct geocoding: returns an array of matching location objects (top-level array)
geocoding_reverse/geo/1.0/reverseGET(top-level array)Reverse geocoding: returns an array of matching location objects
air_pollution/data/2.5/air_pollutionGETlistCurrent air pollution: response contains list array of measurements
historical_onecall/data/3.0/onecall/timemachineGEThourly, currentHistorical weather (time machine): response includes hourly array and current object
weather_map_layer/data/2.5/map/{layer}/{z}/{x}/{y}GET(binary/image)Weather map tiles (tile image binary responses)
stations/data/3.0/stationsGET(depends)Weather station management endpoints (requires paid plan; responses vary)

How do I authenticate with the OpenWeatherMap API?

Authentication is done via an API key. Include it in every request as the appid query parameter (e.g. &appid=YOUR_KEY). Some newer product docs also accept the API key via Authorization headers for paid plans, but the canonical method is the appid query parameter.

1. Get your credentials

  1. Create an account at https://home.openweathermap.org/users/sign_up 2) Login and go to "API keys" (https://home.openweathermap.org/api_keys) 3) Create or copy your API key string 4) Use that key as the appid query parameter (or set as your client header if supported by the endpoint)

2. Add them to .dlt/secrets.toml

[sources.open_weather_source] api_key = "your_api_key_here"

dlt reads this automatically at runtime — never hardcode tokens in your pipeline script. For production environments, see setting up credentials with dlt for environment variable and vault-based options.


How do I set up and run the pipeline?

Set up a virtual environment and install dlt:

uv venv && source .venv/bin/activate uv pip install "dlt[workspace]"

1. Install the dlt AI Workbench:

dlt ai init --agent <your-agent> # <agent>: claude | cursor | codex

This installs project rules, a secrets management skill, appropriate ignore files, and configures the dlt MCP server for your agent. Learn more →

2. Install the rest-api-pipeline toolkit:

dlt ai toolkit rest-api-pipeline install

This loads the skills and context about dlt the agent uses to build the pipeline iteratively, efficiently, and safely. The agent uses MCP tools to inspect credentials — it never needs to read your secrets.toml directly. Learn more →

3. Start LLM-assisted coding:

Use /find-source to load data from the OpenWeatherMap API into DuckDB.

The rest-api-pipeline toolkit takes over from here — it reads relevant API documentation, presents you with options for which endpoints to load, and follows a structured workflow to scaffold, debug, and validate the pipeline step by step.

4. Run the pipeline:

python open_weather_pipeline.py

If everything is configured correctly, you'll see output like this:

Pipeline open_weather_pipeline load step completed in 0.26 seconds 1 load package(s) were loaded to destination duckdb and into dataset open_weather_data The duckdb destination used duckdb:/open_weather.duckdb location to store data Load package 1749667187.541553 is LOADED and contains no failed jobs

Inspect your pipeline and data:

dlt pipeline open_weather_pipeline show

This opens the Pipeline Dashboard where you can verify pipeline state, load metrics, schema (tables, columns, types), and query the loaded data directly.


Python pipeline example

This example loads current_weather and one_call_3 from the OpenWeatherMap API into DuckDB. It mirrors the endpoint and data selector configuration from the table above:

import dlt from dlt.sources.rest_api import RESTAPIConfig, rest_api_resources @dlt.source def open_weather_source(api_key=dlt.secrets.value): config: RESTAPIConfig = { "client": { "base_url": "https://api.openweathermap.org", "auth": { "type": "api_key", "api_key": api_key, }, }, "resources": [ {"name": "current_weather", "endpoint": {"path": "data/2.5/weather"}}, {"name": "one_call_3", "endpoint": {"path": "data/3.0/onecall", "data_selector": "hourly"}} ], } yield from rest_api_resources(config) def get_data() -> None: pipeline = dlt.pipeline( pipeline_name="open_weather_pipeline", destination="duckdb", dataset_name="open_weather_data", ) load_info = pipeline.run(open_weather_source()) print(load_info)

To add more endpoints, append entries from the resource table to the "resources" list using the same name, path, and data_selector pattern.


How do I query the loaded data?

Once the pipeline runs, dlt creates one table per resource. You can query with Python or SQL.

Python (pandas DataFrame):

import dlt data = dlt.pipeline("open_weather_pipeline").dataset() sessions_df = data.current_weather.df() print(sessions_df.head())

SQL (DuckDB example):

SELECT * FROM open_weather_data.current_weather LIMIT 10;

In a marimo or Jupyter notebook:

import dlt data = dlt.pipeline("open_weather_pipeline").dataset() data.current_weather.df().head()

See how to explore your data in marimo Notebooks and how to query your data in Python with dataset.


What destinations can I load OpenWeatherMap data to?

dlt supports loading into any of these destinations — only the destination parameter changes:

DestinationExample value
DuckDB (local, default)"duckdb"
PostgreSQL"postgres"
BigQuery"bigquery"
Snowflake"snowflake"
Redshift"redshift"
Databricks"databricks"
Filesystem (S3, GCS, Azure)"filesystem"

Change the destination in dlt.pipeline(destination="snowflake") and add credentials in .dlt/secrets.toml. See the full destinations list.


Troubleshooting

Authentication failures

If you get HTTP 401 or responses saying "Invalid API key" or "Invalid appid", verify the API key in your secrets.toml and that you are sending it as the appid query parameter. Ensure there are no accidental quotes/whitespace and that the key is active in your OpenWeather account.

Rate limiting and usage

OpenWeather imposes request limits depending on your plan. Free‑tier endpoints are served from api.openweathermap.org; paid subscriptions may use different hostnames. If you receive HTTP 429 Too Many Requests, implement exponential backoff and reduce request frequency. The provider recommends not calling more than once per 10 minutes per location for typical model updates.

Pagination and large responses

Forecast endpoints return arrays (e.g., list, hourly, daily). Use the provided arrays directly; endpoints typically return a single response containing the full set for the requested time window (no cursor‑based pagination). For geocoding, several matches are returned as a top‑level array — pick the first exact match or present options to users.

Common API errors

  • 401 Unauthorized / "Invalid API key" — bad or missing appid
  • 403 Forbidden — access to a paid product or restricted resource without proper subscription
  • 404 Not Found — bad endpoint path or invalid parameters
  • 429 Too Many Requests — quota exceeded / rate limit
  • 500 / 502 / 503 — server errors; retry with backoff

Ensure that the API key is valid to avoid 401 Unauthorized errors. Also, verify endpoint paths and parameters to avoid 404 Not Found errors.


Next steps

Continue your data engineering journey with the other toolkits of the dltHub AI Workbench:

  • data-exploration — Build custom notebooks, charts, and dashboards for deeper analysis with marimo notebooks.
  • dlthub-runtime — Deploy, schedule, and monitor your pipeline in production.
dlt ai toolkit data-exploration install dlt ai toolkit dlthub-runtime install

Was this page helpful?

Community Hub

Need more dlt context for OpenWeatherMap?

Request dlt skills, commands, AGENT.md files, and AI-native context.