Search code examples
pythonpython-3.xurllib2urllib

How to structure a request to neutrinoapi using python 3? (convert urllib2 request to urllib)


Im new to server side code and interested in using the neutrinoapi (www.neutrinoapi.com) for filtering some bad words out of text. I have written the following code in Python 3 (im using bottle server):

url = 'https://neutrinoapi.com/bad-word-filter'
params = {
    'user-id': 'testing',
    'api-key': '205cmqorLBdyV2F9FX4z6NNq1Y3z8AkRTw8ImtGE2MtzxmhT',
    'ip': '162.209.104.195'
}

json_data = json.dumps(params).encode('utf8')
response = urllib.request.urlopen(url, data = json_data)
result = json.loads(response.read())

This request is returning the following error:

raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden

The example on the website is at this link: https://www.neutrinoapi.com/api/api-examples/python/

Examples provided are using python 2.7 and urllib2 which i understand is now built into urllib. Cant seem to get the request to work in Python 3. Any ideas on how to make a proper request?


Solution

  • The Python example doesn't use JSON for the parameters, only for the response. You'll need to URL encode those parameters instead; use the urllib.parse.urlencode() function for that, then encode the resulting string to bytes.

    You also need to send the content parameter for a bad-word-filter request, not an IP address:

    from urllib.parse import urlencode
    
    url = 'https://neutrinoapi.com/bad-word-filter'
    params = {
        'user-id': 'testing',
        'api-key': '<valid api key>',
        'content': 'foo bar baz'
    }
    
    encoded_params = urlencode(params).encode('utf8')
    response = urllib.request.urlopen(url, data = encoded_params)
    result = json.loads(response.read())