dataretrieval-python
A Python alternative to USGS-R's dataRetrieval package for obtaining USGS or EPA water quality data, streamflow data, and metadata directly from web services.
https://github.com/DOI-USGS/dataretrieval-python
Category: Natural Resources
Sub Category: Water Supply and Quality
Keywords from Contributors
hydrology usgs water groundwater ow climate modflow prms hydrology-modeling
Last synced: about 13 hours ago
JSON representation
Repository metadata
Python package for retrieving water data from USGS or the multi-agency Water Quality Portal
- Host: GitHub
- URL: https://github.com/DOI-USGS/dataretrieval-python
- Owner: DOI-USGS
- License: other
- Created: 2018-09-27T14:05:26.000Z (about 8 years ago)
- Default Branch: main
- Last Pushed: 2026-12-02T22:48:28.000Z (3 days ago)
- Last Synced: 2026-12-04T22:03:44.051Z (about 13 hours ago)
- Language: Python
- Homepage: https://doi-usgs.github.io/dataretrieval-python/
- Size: 177 MB
- Stars: 272
- Watchers: 11
- Forks: 67
- Open Issues: 27
- Releases: 25
-
Metadata Files:
- Readme: README.md
- Changelog: NEWS.md
- Contributing: CONTRIBUTING.md
- License: LICENSE.md
- Agents: AGENTS.md
README.md
dataretrieval: Download hydrologic data
What is dataretrieval?
dataretrieval simplifies loading hydrologic data into Python. Like the
original R version
dataRetrieval, it retrieves the
major U.S. Geological Survey (USGS) hydrology data types available on the Web.
It also retrieves data from the Water Quality Portal (WQP), the National
Ground-Water Monitoring Network (NGWMN), and the Network Linked Data Index
(NLDI).
Check the NEWS for all updates and announcements.
Installation
Install dataretrieval using pip:
pip install dataretrieval
Or conda:
conda install -c conda-forge dataretrieval
Or directly from GitHub:
pip install git+https://github.com/DOI-USGS/dataretrieval-python.git
Usage Examples
Water Data API
Access USGS water-monitoring data.
Important: Users are strongly encouraged to obtain an API key for higher rate limits. Register for an API key, then supply it in whichever of these ways suits you. They are listed from highest to lowest precedence, so an explicit block or deployment environment can override a file without editing it:
# 1. a configure() block - for one call, an interactive prompt, or when
# different threads/tasks need different credentials.
from getpass import getpass
import dataretrieval
from dataretrieval import Configuration, waterdata
with dataretrieval.configure(Configuration(api_key=getpass("USGS API key: "))):
df, metadata = waterdata.get_daily(monitoring_location_id="USGS-01646500")
# 2. an environment variable (the R dataRetrieval package uses the same
# variable, so one export serves both)
export API_USGS_PAT="your_api_key_here"
# 3. ~/.dataretrieval/config.toml - keeps the key out of your shell
# environment, where every process you start inherits it.
# Restrict it afterwards: chmod 600 ~/.dataretrieval/config.toml
api_key = "your_api_key_here"
dataretrieval.show_configuration() reports what is in effect and where each setting
came from, without printing the key. Concurrency, retries, and the progress
line are configured the same way, and can be narrowed to one service: a
configure() block takes at most one configuration per adapter, each either
built in code or loaded by name from a profile in the file.
from dataretrieval.ngwmn import NgwmnConfiguration
from dataretrieval.waterdata import WaterdataConfiguration
with dataretrieval.configure(
WaterdataConfiguration.load("overnight"), # a profile in config.toml
NgwmnConfiguration(concurrency=2), # built here
):
...
See the configuration guide.
The following example retrieves daily streamflow data for a specific
monitoring location. The / in the time argument separates the start and
end of the desired range:
from dataretrieval import waterdata
# Get daily streamflow data (returns DataFrame and metadata)
df, metadata = waterdata.get_daily(
monitoring_location_id="USGS-01646500",
parameter_code="00060", # Discharge
time="2024-10-01/2025-09-30",
)
print(f"Retrieved {len(df)} records")
print(f"Site: {df['monitoring_location_id'].iloc[0]}")
print(f"Mean discharge: {df['value'].mean():.2f} {df['unit_of_measure'].iloc[0]}")
Retrieve streamflow at multiple locations from October 1, 2024 to the present:
df, metadata = waterdata.get_daily(
monitoring_location_id=["USGS-13018750", "USGS-13013650"],
parameter_code="00060",
time="2024-10-01/..",
)
print(f"Retrieved {len(df)} records")
Retrieve location information for all monitoring locations categorized as stream sites in Maryland:
# Get monitoring location information
df, metadata = waterdata.get_monitoring_locations(
state="Maryland", # full name, postal code ('MD'), or FIPS ('24')
site_type_code="ST", # Stream sites
)
print(f"Found {len(df)} stream monitoring locations in Maryland")
Finally, retrieve continuous (a.k.a. "instantaneous") data for one location. We strongly advise breaking continuous data requests into smaller time windows to avoid timeouts and other issues:
# Get continuous data for a single monitoring location and water year
df, metadata = waterdata.get_continuous(
monitoring_location_id="USGS-01646500",
parameter_code="00065", # Gage height
time="2024-10-01/2025-09-30",
)
print(f"Retrieved {len(df)} continuous gage height measurements")
Speeding up large downloads with parallel_chunks
By default the getters split a multi-value request only as far as the server's
~8 KB URL limit forces — the fewest sub-requests. For a large, paginated
pull, that default is needlessly conservative: every sub-request pages through
its own results, so dividing the query into more, smaller sub-requests lets
those pages be fetched in parallel. parallel_chunks(n) opts a single call
into that finer split, fanning it out into n sub-requests. The finer split
helps only when the result is large enough to span many pages and the query
has a multi-value argument to divide, such as a list of monitoring locations. On
a small query — or one with nothing to split — it only adds requests, so
parallel_chunks is a deliberate, scoped with block, never the default.
from dataretrieval import waterdata
# All stream gages in Ohio, then 20 years of their daily discharge — large
# enough to span many pages, so it benefits from a finer split.
sites, _ = waterdata.get_monitoring_locations(state="Ohio", site_type_code="ST")
with waterdata.parallel_chunks(32): # request up to 32 optional chunks
df, md = waterdata.get_daily(
monitoring_location_id=sites["monitoring_location_id"],
parameter_code="00060", # discharge
time="2004-01-01/2023-12-31",
)
n is the number of sub-requests to fan the call out into, capped by how many
values there are to split. Each sub-request costs a request against your hourly
rate limit. How many run at once is
capped separately by API_USGS_CONCURRENT (default 32), so the useful range is
roughly 2 up to that value.
Benchmark — a fixed 271-site subset of Ohio stream gages
(get_daily, parameter_code="00060"), with a small fixed page size
(limit=250) so every run fetches roughly the same number of pages (isolating
the effect of parallelism). Each n ran against its own cold 1-year time
window, so no run is served from the server's data-window cache:
| n | optional fan-out | pages | wall-clock | speedup |
| ---- | ---------------- | ----- | ---------------------- | ------- |
| off | 1 | ~30 | 9.5 s / 9.1 s (2 runs) | 1× |
| 8 | 8 | ~32 | 2.2 s / 1.9 s | ~4.5× |
| 32 | 32 | 54 | 1.2 s | ~8× |
The gain comes from overlapping each sub-request's per-page latency and
server-side work. The exact multiplier therefore scales with how many pages the
pull spans: a larger pull (more pages) has more parallelism to exploit. The
extra sub-requests each cost quota, so reserve a large n for pulls you know
are large.
Visit the API Reference for more information and examples on available services and input parameters.
For verbose troubleshooting and support — including the request URL sent to the API — enable debug-level logging:
import logging
logging.basicConfig(level=logging.DEBUG)
National Ground-Water Monitoring Network (NGWMN)
Access groundwater data aggregated from many state, federal, and local agencies. NGWMN uses the same OGC engine as the Water Data API, so chunking and pagination behave the same way:
from dataretrieval import ngwmn
# Find the groundwater monitoring sites in a state
# (state accepts a full name, a postal code like 'WI', or a FIPS code like '55')
sites, metadata = ngwmn.get_sites(state="Wisconsin")
print(f"Found {len(sites)} NGWMN sites in Wisconsin")
# Pull water levels from the first twenty sites over a time window.
water_levels, metadata = ngwmn.get_water_level(
monitoring_location_id=sites["monitoring_location_id"][:20],
datetime=["2022-01-01", "2024-01-01"],
)
print(f"Retrieved {len(water_levels)} water-level observations")
Water Quality Portal (WQP)
Access water quality data from multiple agencies:
from dataretrieval import wqp
# Find water quality monitoring sites (returns a DataFrame and metadata)
sites, metadata = wqp.what_sites(
statecode="US:55", # Wisconsin
siteType="Stream",
)
print(f"Found {len(sites)} stream monitoring sites in Wisconsin")
# Get water quality results
results, metadata = wqp.get_results(
siteid="USGS-05427718", characteristicName="Temperature, water"
)
print(f"Retrieved {len(results)} temperature measurements")
Network Linked Data Index (NLDI)
Discover and navigate hydrologic networks:
from dataretrieval import nldi
# Get watershed basin for a stream reach
basin = nldi.get_basin(
feature_source="comid",
feature_id="13293474", # NHD reach identifier
)
print(f"Basin contains {len(basin)} feature(s)")
# Find upstream flowlines
flowlines = nldi.get_flowlines(
feature_source="comid",
feature_id="13293474",
navigation_mode="UT", # Upstream tributaries
distance=50, # km
)
print(f"Found {len(flowlines)} upstream tributaries within 50km")
Water Use (NWDC)
Retrieve modeled water-use estimates from the National Water Availability Assessment Data Companion:
from dataretrieval import nwdc
# Monthly public-supply withdrawals for Rhode Island, split into
# groundwater and surface-water sources (returns a DataFrame and metadata).
df, metadata = nwdc.get_wateruse(
model="wu-public-supply-wd",
variable=["pswdtot", "pswdgw", "pswdsw"],
state="RI", # name/postal/FIPS; pass a list to fan out over several areas
start_date="2020-01",
time_resolution="monthly",
)
print(f"Retrieved {len(df)} records across {df['huc12_id'].nunique()} watersheds")
# Aggregate the HUC12 grid to a statewide monthly total (million gallons/day)
statewide = df.groupby("year_month")["pswdtot_mgd"].sum()
print(statewide.head())
Available Data Services
Modern USGS Water Data APIs — dataretrieval.waterdata
get_daily: Daily statistical summaries (mean, min, max)get_continuous: High-frequency continuous (instantaneous) valuesget_field_measurements: Discrete measurements from field visitsget_peaks: Annual peak streamflowget_monitoring_locations: Site information and metadataget_time_series_metadata: A location's available data parametersget_latest_daily: Most recent daily statistical summaryget_latest_continuous: Most recent high-frequency valueget_stats_por/get_stats_date_range: Daily, monthly, and annual statisticsget_samples: Discrete USGS water-quality samplesget_ratings: Stage-discharge rating curves
National Ground-Water Monitoring Network (NGWMN) — dataretrieval.ngwmn
get_sites: Groundwater monitoring-location metadata across many agenciesget_water_level: Depth-to-water and water-level observationsget_lithology: Geologic-material logs by depth intervalget_well_construction: Casing, screen, and build-out recordsget_providers: Contributing data-provider organizations
Water Quality Portal — dataretrieval.wqp
get_results: Water-quality analytical results from USGS, EPA, and other agencieswhat_sites: Monitoring-location informationwhat_organizations: Data-provider informationwhat_projects: Sampling-project details
Network Linked Data Index (NLDI) — dataretrieval.nldi
get_basin: Watershed boundary for a point or featureget_flowlines: Upstream/downstream flowline navigationget_features: Find monitoring sites, dams, and other features along the networkget_features_by_data_source: Features from a specific data source
NWDC (National Water Availability Assessment Data Companion) — dataretrieval.nwdc
get_wateruse: Modeled water-use estimates — public-supply, irrigation, and thermoelectric withdrawals and consumptive use — on a national 12-digit hydrologic-unit (HUC12) grid, summarizable to counties, states, or coarser hydrologic units
More Examples
Explore additional examples in the
demos
directory, including Jupyter notebooks demonstrating advanced usage patterns.
Getting Help
- Issue tracker: Report bugs and request features at https://github.com/DOI-USGS/dataretrieval-python/issues
- Documentation: https://doi-usgs.github.io/dataretrieval-python/
Contributing
Contributions are welcome! See CONTRIBUTING.md for development guidelines.
Acknowledgments
This material is partially based upon work supported by the National Science Foundation (NSF) under award 1931297. Any opinions, findings, conclusions, or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the NSF.
Disclaimer
This software is preliminary or provisional and is subject to revision. It is being provided to meet the need for timely best science. The software has not received final approval by the U.S. Geological Survey (USGS). No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. The software is provided on the condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from the authorized or unauthorized use of the software.
Citation
Hodson, T.O., Hariharan, J.A., Black, S., and Horsburgh, J.S., 2023, dataretrieval (Python): a Python package for discovering and retrieving water data available from U.S. federal hydrologic web services: U.S. Geological Survey software release, https://doi.org/10.5066/P94I5TX3.
Owner metadata
- Name: U.S. Geological Survey
- Login: DOI-USGS
- Email: gs_help_git@usgs.gov
- Kind: organization
- Description: By integrating our diverse scientific expertise, we understand complex natural science phenomena and provide scientific products that lead to solutions.
- Website: https://www.usgs.gov/
- Location: United States of America
- Twitter: USGS
- Company:
- Icon url: https://avatars.githubusercontent.com/u/65027635?v=4
- Repositories: 59
- Last ynced at: 2026-12-04T20:28:13.266Z
- Profile URL: https://github.com/DOI-USGS
GitHub Events
Total
- Create event: 3
- Delete event: 1
- Fork event: 13
- Issue comment event: 52
- Issues event: 23
- Pull request event: 42
- Pull request review comment event: 55
- Pull request review event: 48
- Push event: 99
- Release event: 4
- Watch event: 49
Last Year
- Delete event: 1
- Fork event: 3
- Issue comment event: 15
- Issues event: 15
- Pull request event: 27
- Pull request review comment event: 41
- Pull request review event: 31
- Push event: 88
- Release event: 2
- Watch event: 8
Committers metadata
Last synced: 1 day ago
Total Commits: 533
Total Committers: 32
Avg Commits per committer: 16.656
Development Distribution Score (DDS): 0.43
Commits in past year: 293
Committers in past year: 14
Avg Commits per committer in past year: 20.929
Development Distribution Score (DDS) in past year: 0.235
| Name | Commits | |
|---|---|---|
| Timothy Hodson | 3****s | 304 |
| Elise Hinman | e****n@u****v | 153 |
| J. Hariharan | j****n@u****v | 22 |
| Scott Black | s****k@u****u | 8 |
| Pabitra Dash | p****a@h****m | 5 |
| Joseph Stachelek | j****a | 4 |
| Bhaskar Gurram | g****i@g****m | 4 |
| nodohs | t****n@R****l | 3 |
| Arpit Jain | 3****9 | 2 |
| Joshua Larsen | j****n@u****v | 2 |
| nodohs | t****n@g****m | 2 |
| Ibrahim El Merehbi | e****i | 2 |
| Doug Dennis | d****r@g****m | 2 |
| Dave Tapley | d****e@t****m | 2 |
| Dukotah Hutcheon | D****h@g****m | 1 |
| Austin Raney | a****y@n****v | 1 |
| Camilo J. Bastidas Pacheco | c****s@g****m | 1 |
| Copilot | 1****t | 1 |
| David Blodgett | d****t@u****v | 1 |
| Edwin | 3****c | 1 |
| Jessamyn Smith | j****h@g****m | 1 |
| Joe Zemmels (he/him) | j****s@g****m | 1 |
| Justin Bousquin | j****n@y****m | 1 |
| Keith Doore | 5****e | 1 |
| Kyunghan Bae | 7****2 | 1 |
| Laura DeCicco | l****o@u****v | 1 |
| Lee Stanish | 8****s | 1 |
| MLR | m****1@g****m | 1 |
| Sai Asish Y | s****5@g****m | 1 |
| Tevinch | t****g@l****m | 1 |
| and 2 more... | ||
Committer domains:
- usgs.gov: 6
- noaa.gov: 1
- tapley.com: 1
- usu.edu: 1
Issue and Pull Request metadata
Last synced: 3 days ago
Total issues: 130
Total pull requests: 276
Average time to close issues: 6 months
Average time to close pull requests: 12 days
Total issue authors: 59
Total pull request authors: 31
Average comments per issue: 1.74
Average comments per pull request: 0.87
Merged pull request: 201
Bot issues: 0
Bot pull requests: 0
Past year issues: 32
Past year pull requests: 188
Past year average time to close issues: 17 days
Past year average time to close pull requests: 11 days
Past year issue authors: 13
Past year pull request authors: 13
Past year average comments per issue: 0.72
Past year average comments per pull request: 0.45
Past year merged pull request: 125
Past year bot issues: 0
Past year bot pull requests: 0
Top Issue Authors
- thodson-usgs (31)
- ehinman (11)
- lstanish-usgs (7)
- elbeejay (6)
- davetapley (6)
- SorooshMani-NOAA (5)
- putmanannie (4)
- wangzcl (2)
- DrToom (2)
- msweier (2)
- bhaskargurram-ai (2)
- jsta (2)
- qorud02 (2)
- jpouliot10 (2)
- pkdash (2)
Top Pull Request Authors
- thodson-usgs (184)
- elbeejay (21)
- ehinman (19)
- jsta (5)
- pkdash (4)
- davetapley (4)
- sblack-usu (4)
- cjbas22 (3)
- bhaskargurram-ai (3)
- elmerehbi (3)
- edsaac (2)
- nodohs (2)
- qorud02 (2)
- arpitjain099 (2)
- jlarsen-usgs (2)
Top Issue Labels
- enhancement (8)
- bug (8)
- ready-for-agent (6)
- documentation (5)
- question (4)
Top Pull Request Labels
- enhancement (9)
- bug (8)
- v1 (6)
- documentation (3)
- exploration (3)
- refactor (2)
- v2 (2)
- upstream bug (1)
Package metadata
- Total packages: 3
-
Total downloads:
- pypi: 41,043 last-month
- Total dependent packages: 8 (may contain duplicates)
- Total dependent repositories: 11 (may contain duplicates)
- Total versions: 73
- Total maintainers: 3
pypi.org: dataretrieval
Discover and retrieve water data from U.S. federal hydrologic web services.
- Homepage:
- Documentation: https://dataretrieval.readthedocs.io/
- Licenses: CC0-1.0
- Latest release: 1.5.0 (published 3 days ago)
- Last Synced: 2026-12-02T23:01:48.193603Z (2 days ago)
- Versions: 29
- Dependent Packages: 8
- Dependent Repositories: 11
- Downloads: 41,043 Last month
-
Rankings:
- Dependent packages count: 1.865%
- Average: 3.454%
- Downloads: 4.125%
- Dependent repos count: 4.373%
- Maintainers (3)
proxy.golang.org: github.com/DOI-USGS/dataretrieval-python
- Homepage:
- Documentation: https://pkg.go.dev/github.com/DOI-USGS/dataretrieval-python#section-documentation
- Licenses: other
- Latest release: v1.4.0 (published 2 months ago)
- Last Synced: 2026-12-03T21:34:26.078484Z (1 day ago)
- Versions: 22
- Dependent Packages: 0
- Dependent Repositories: 0
-
Rankings:
- Dependent packages count: 5.401%
- Average: 5.583%
- Dependent repos count: 5.764%
proxy.golang.org: github.com/doi-usgs/dataretrieval-python
- Homepage:
- Documentation: https://pkg.go.dev/github.com/doi-usgs/dataretrieval-python#section-documentation
- Licenses: other
- Latest release: v1.4.0 (published 2 months ago)
- Last Synced: 2026-12-03T21:34:21.492332Z (1 day ago)
- Versions: 22
- Dependent Packages: 0
- Dependent Repositories: 0
-
Rankings:
- Dependent packages count: 5.401%
- Average: 5.583%
- Dependent repos count: 5.764%
Dependencies
- actions/checkout v2 composite
- actions/setup-python v2 composite
- actions/checkout v3 composite
- actions/setup-python v3 composite
- pypa/gh-action-pypi-publish 27b31702a0e7fc50959f5ad993c78deac1bdfc29 composite
- JamesIves/github-pages-deploy-action v4.4.1 composite
- actions/checkout v3 composite
- boto3 *
- dataretrieval *
- lithops *
- pika *
- ps_mem *
- pyarrow *
- s3fs *
- tblib *
- pandas ==2.*
- requests *
- actions/checkout v6 composite
- actions/setup-python v6 composite
- actions/upload-artifact v4 composite
- actions/checkout v6 composite
- actions/setup-python v6 composite
Score: 19.789090932364708