Python Forum

Full Version: API Request / JSON
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am having difficulty pulling data from an API which says that parameter content needs to be application/json. Here is the link to the the api notes http://www.nfib-sbet.org/developers/

Here is the code I have:

url = "http://open.api.nfib-sbet.org/rest/sbetdb/_proc/getIndicators"
headers = {
    "Content-Type": "application/json",
    "app_name": "sbet"
}

data = {
    "params": [
        { "name": "minYear", "param_type": "IN", "value": 2010 },
        { "name": "minMonth", "param_type": "IN", "value": 6 },
        { "name": "maxYear", "param_type": "IN", "value": 2010 },
        { "name": "maxMonth", "param_type": "IN", "value": 12 },
        { "name": "indicator", "param_type": "IN", "value": "OPT_INDEX" }
    ]
}

response = requests.post(url, headers=headers, data=json.dumps(data))
I keep getting 400 responses. I tried a few slightly different variations but nothing seems to work. I've looked through the api notes and can't figure out what i'm doing wrong. any help would be much appreciated.

Matt
I think there is problem with this Api,as i tried different thing and it dos no work.
A quick search there one post out there.
So there add app_name in url this dos not work now,and it seems the Api is not supported since 2017.
I see. That's too bad. Thanks for your help anyways!
As you are using the requests library in Python to make a POST request to the NFIB SBET API. The 400 response you are getting indicates that there is likely an issue with the request you are sending to the API.

Data parameter should contain a JSON object with the request parameters. However, in your code, you are using the data parameter to send the JSON data. To properly send the JSON data, you should use the json parameter instead.

import requests
import json

url = "http://open.api.nfib-sbet.org/rest/sbetdb/_proc/getIndicators"
headers = {
    "Content-Type": "application/json",
    "app_name": "sbet"
}

data = {
    "params": [
        { "name": "minYear", "param_type": "IN", "value": 2010 },
        { "name": "minMonth", "param_type": "IN", "value": 6 },
        { "name": "maxYear", "param_type": "IN", "value": 2010 },
        { "name": "maxMonth", "param_type": "IN", "value": 12 },
        { "name": "indicator", "param_type": "IN", "value": "OPT_INDEX" }
    ]
}

response = requests.post(url, headers=headers, json=data)

print(response.status_code)
print(response.json())
By using the json parameter instead of the data parameter, the requests library will automatically set the Content-Type header to "application/json" and encode the JSON data correctly.