kqtran

Boolean API Requests in Python

·

curlconverter is extremely helpful for helping beginners format requests in Python.

I used it to translate this, provided by the Sophos API:

curl --request POST \
  'https://api-{dataRegion}.central.sophos.com/endpoint/v1/endpoints/guid/tamper-protection' \
  --header 'X-Tenant-ID: guid' \
  --header 'Authorization: Bearer [YOUR_AUTH_INFO]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"enabled":false}' \
  --compressed

into this:

import requests

headers = {
    'X-Tenant-ID': guid,
    'Authorization': 'Bearer [YOUR_AUTH_INFO]',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
}

data = '{"enabled":false}'
response = requests.post(url, headers=headers, data=data)

That kept returning 200 Bad Request. The API docs state the correct structure.


post:
  requestBody:
    description: "Sends a request to update Tamper Protection settings."
    required: true
      application/json:
        schema:
          type: "object"
          description: "A request to change Tamper Protection settings for the\
            \ endpoint."
          properties:
            enabled:
              description: "Whether Tamper Protection should be turned on for\
                \ the endpoint."
              type: "boolean"

In order to form this request correctly, you must import json and use json.dumps.

import requests
import json

headers = {
    'X-Tenant-ID': guid,
    'Authorization': 'Bearer [YOUR_AUTH_INFO]',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
}

data = json.dumps({ 'enabled': False })
requests.post(url, headers=headers, data=data)