Kickdak
Kickdak

Reputation: 337

Python API Upload file Post

I am trying too upload a file through an API with Python. I have almost got it but i cant seem to get the data part right. The link shows how it works and my code is under. https://bimsync.com/developers/reference/api/v2#create-revision

How i should write the code to send the data?

  def create_new_revision(self, project_id, model_id, filepath):
    with open("API_INFO.json", "r") as jsonFile:
        info = json.load(jsonFile)

    headers = {
        'Authorization': 'Bearer {}'.format(info["access_token"]),
        'Content-Type': 'application/ifc',
        "Bimsync-Params": {"callbackUri": "https://example.com",
                           "comment": "added some windows",
                           "filename": "mk.ifc",
                           "model": "{}".format(model_id)}}

    files = open("mk.ifc", "rb")
    data = {files, "mk.ifc"}

    print(headers)
    print("Createing new revision for model:")
    requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, data=data)

Upvotes: 0

Views: 192

Answers (2)

Sylvain M.
Sylvain M.

Reputation: 26

2 issues:

  1. Requests needs the headers to be carefully crafted. JSON needs to be string-ified thanks to json.dumps():
    headers = { 
      'Authorization': 'Bearer {}'.format(info['access_token']),
      'Content-Type': 'application/ifc',
      'Bimsync-Params': json.dumps({'callbackUri': 'https://example.com',
          'comment': 'added some windows',
          'filename': 'NURBS.ifc',
          'model': '{}'.format(model_id)
      })
    }
  1. The Bimsync API documentation states that the IFC file content will be posted in the request body, not the file name:
    ifcfile = open("{}".format(filepath), 'r')
    data= ifcfile.read()
    ...
    result = requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, data=data)

And voilà.

Upvotes: 1

LeKhan9
LeKhan9

Reputation: 1350

It's a bit tough to test your exact service since I don't have a token. I think you are close though. How about passing the files key?

files = {'filename': open('mk.ifc','rb')}

and then adding this to the POST

    requests.post(r'https://api.bimsync.com/v2/projects/{}/revisions'.format(project_id), headers=headers, files=files)

Hope this helps!

Upvotes: 0

Related Questions