Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the USDA API

I am trying to follow the instructions for pulling data from market news api from USDA in python, https://mymarketnews.ams.usda.gov/mymarketnews-api/authentication, but I get a 401 error

import requests
url = 'https://marsapi.ams.usda.gov/services/v1.2/reports'
headers={'x-api-key':'mars_test_343343'}

resp = requests.get(url, headers= headers)
print(resp.status_code) 

I can't get it to work, the documentation says " In your software, use the API key as the basic authentication username value. You do not need to provide a password. ", I am pretty new to API calls, how do I provide my username as the api-key so the server authenticates me?

Note: I am using my actual api-key in the code instead of 'mars_test_343343'

like image 248
Edu Galindo Avatar asked Nov 24 '25 11:11

Edu Galindo


1 Answers

Basic Authentication works a little differently with the requests library. You can do something like this instead:

from requests.auth import HTTPBasicAuth
resp = requests.get(url, auth=HTTPBasicAuth('mars_test_343343', None)

Note that because of the vagueness of "not needing to provide a password", the None value may need to be an empty string '' instead.

like image 107
Stephen Avatar answered Nov 26 '25 01:11

Stephen