Vasai
Vasai

Reputation: 89

How to POST JSON file with Python Requests?

I am writing a python function to send SBOM reports to Dependency-Track via API.
Sending SBOM manually using curl is successful:

curl -X "POST" "https://dtrack.example.com/api/v1/bom" \
    -H 'accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -H "X-Api-Key: my_token" \
    -F "project=e81e5ed3-66f3-490d-8296-3b69618bad60" \
    -F "projectVersion=3.18.4" \
    -F "[email protected]"

Rewrote this query into a python function:

def upload_bom(file_path, project_uuid, project_version):
    url = "https://dtrack.example.com/api/v1/bom"
    headers = {
    "Accept": "application/json",
    "X-Api-Key": "my_token",
    'Content-Type': 'multipart/form-data'
    }
    data = {
        "project": project_uuid,
        "projectVersion": project_version
    }
    file_name = Path(file_path).name
    with open(file_path, "rb") as bom_file:
        data['bom'] = (file_name, bom_file)

    response = requests.post(url, headers=headers, data=data)
    return [response.status_code, response.content] 

When calling this function with similar parameters, I get an error:

500 'Uncaught internal server error'

There is no information in the Dependency-Track logs either, which may help.

I tried passing SBOM file not in data, but separately.
But it didn't work.

    data = {
        "project": project_uuid,
        "projectVersion": project_version
    }
    with open(file_path, 'rb') as bom_file:
        files = {'bom': bom_file}

Unfortunately I couldn't find what this problem is related to, maybe someone has already encountered it and knows the solution?

Upvotes: 0

Views: 333

Answers (2)

Dude
Dude

Reputation: 345

You need to divide metadata from the actual file you're trying to post. Try below update in your code:

    data = {
        "project": project_uuid,
        "projectVersion": project_version
    }
    files = {'bom': open(file_path, 'rb')}

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

Upvotes: 0

César Rodrigues
César Rodrigues

Reputation: 86

Have you tried converting data using the json library?

import json

data = json.dumps({"project": project_uuid, "projectVersion": project_version})

Also, maybe sending the file in a list instead of a set:

file_name = Path(file_path).name
    with open(file_path, "rb") as bom_file:
        data['bom'] = [file_name, bom_file] #changed this to a list

Upvotes: 0

Related Questions