USGS Water Services
ScienceAccessing USGS Water Services API with JavaScript
If you are looking for a way to access hydrological data for rivers, streams, and other bodies of water across the United States, then the USGS Water Services API is a great resource to use. This public API provides access to a wealth of data, including real-time streamflow data, water quality data, groundwater levels, and much more.
In this blog post, we will explore how to access the USGS Water Services API with JavaScript and provide some useful example code to get you started.
Setting up the API Request
The first step to accessing the USGS Water Services API with JavaScript is to make an API request. You can use the fetch()
method to make a GET request to the API endpoint URL and pass in any necessary parameters as a query string.
Here's an example of how to make an API request to get real-time streamflow data for a specific site:
const siteCode = "01581680";
const url = `https://waterservices.usgs.gov/nwis/iv/?sites=${siteCode}&format=json`;
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data));
In this example, we are using the fetch()
method to make a GET request to the USGS Water Services API endpoint. We are passing in a sites
parameter with a specific site code, and we are requesting the data in JSON format.
Reading API response
Once you have made an API request, you can access the data returned by the API in the then()
method of the fetch()
call. The data returned by the USGS Water Services API is in JSON format, so we can easily parse it using the json()
method of the response object.
Here's how you can access the streamflow data returned by the API:
fetch(url)
.then((response) => response.json())
.then((data) => {
const streamflow = data.value.timeSeries[0].values[0].value[0].value;
console.log(`Streamflow at ${siteCode}: ${streamflow} cfs`);
});
In this example, we are accessing the timeSeries
property of the data object returned by the API. We then access the values
property of the first time series object returned (which corresponds to the real-time streamflow data for the site code we requested). Finally, we access the value
property of the first element of the values
array to get the actual streamflow value.
Conclusion
In this blog post, we have explored how to access the USGS Water Services API with JavaScript. We have seen how to make an API request and how to parse the JSON data returned by the API. With this knowledge, you can now start building your own applications that use the USGS Water Services API to access hydrological data in real-time.