python-3.xazureazure-devopsazure-functionscommon-data-service

Making a PATCH method request with a file to Common Data Service


I'm trying to create a Python script which can use the PATCH method to upload a file into MS's Common data service. I'm successfully making GET, POST, PATCH, and DELETE calls with simple data, but have so far been unable to configure it so that I can upload a file.

I've been using the Requests library for Python, with the requests.patch function in order to try updating the data. I'm attempting to upload a .csv file into the field, the file which i'm uploading has a filesize of 1kb.

If I upload the data directly into the common data service through the in-built data interface, my browser is able to correctly make a PATCH call. I've attempted to copy the call as closely as I can, but have had zero success.

File field in common data service

File field in common data service

PATCH call in web browser

PATCH call in web browser

What is the correct way to make a PATCH request with a file to Microsoft's Common data service?


Solution

  • Made a mistake with the url in my request - I had missed out which field I was uploading data to

    Incorrect URL: 
    https://90g9j3gf.crm4.dynamics.com/api/data/v9.0/test_entity(34cd854c-1175-4778-bf95-e1ce12dea3b0)
    
    Corrected URL: 
    https://90g9j3gf.crm4.dynamics.com/api/data/v9.0/test_entity(34cd854c-1175-4778-bf95-e1ce12dea3b0)/test_field
    

    The code I used to make the request:

    Import requests
    
    http_headers = {
      'Authorization': 'Bearer ' + token['access_token'],
      'Content-Type': 'application/octet-stream',
      'x-ms-file-name': 'test.csv'
    }
    filedata = open("project-folder\\test.csv", "rb")
    patch_req = requests.patch(
      url, # My URL is defined elsewhere
      headers=http_headers,
      data=filedata
    )
    

    This now works correctly for me