Search code examples
pythonpython-requests

Requests package and API documentation


I'm having trouble understanding where to add parameters defined by API documentation. Take BeeBole's documentation for example, which specifies that to get an absence by ID, the following request is required:

{
"service": "absence.get",
"id": "absence_id"
}

They provide only one URL in the documentation:

BeeBole is accepting HTTP POST requests in a json-doc format to the following URL: https://beebole-apps.com/api/v2

How would this be implemented in the context of Python requests? The following code I've tried returns 404:

import requests
    
payload = {
    "service": "absence.get",
    "id": "absence_id"
}

auth = {
    "username": "API_token",
    "password": "x"
}

url = "https://beebole-apps.com/api/v2"

req = requests.get(url, params=payload, auth=auth).json()

Solution

  • BeeBole is accepting HTTP POST resquests in a json-doc format to the following URL: https://beebole-apps.com/api/v2

    The JSON document format here is the part you missed; you need to pass the information as a JSON encoded body of the request. The params argument you used only sets the URL query string (the ?... part in a URL).

    Use

    import requests
    
    payload = {
        "service": "absence.get",
        "id": "absence_id"
    }
    
    auth = ("API_token", "x")    
    url = "https://beebole-apps.com/api/v2"
    
    req = requests.get(url, json=payload, auth=auth).json()
    

    The json= part ensures that the payload dictionary is encoded to JSON and sent as a POST body. This also sets the Content-Type header of the request.

    I've also updated the API authentication, all that the auth keyword needs here is a tuple of the username and password. See the Basic Authentication section.

    You may want to wait with calling .json() on the response; check if the response was successful first:

    req = requests.get(url, json=payload, auth=auth)
    if not req.ok:
        print('Request not OK, status:', req.status_code, req.reason)
        if req.content:
            print(req.text)
    else:
        data = req.json()
        if data['status'] == 'error':
            print('Request error:', data['message'])
    

    This uses the documented error responses.