I am attempting to use Python to add attachments to an ArcGIS Online hosted feature service, but I'm getting an 'Unable to add attachment to the feature.' message when I run the following code:
import requests
objectId = '158'
attachUrl = "http://services.arcgis.com/abcdefg/FeatureServer/0/%s/addAttachment" %objectId
files = {'file': open('myAttachment.pdf', 'rb')}
params = { "token": token, "f": "json", "files": files}
r = requests.post(attachUrl, params)
r.text
The result:
u'{"error":{"code":400,"message":"","details":["Unable to add attachment to the feature."]}}'
I have verfied that I'm using a valud url, objectID, and token.
I believe the issue is with the syntax I'm using to make the multipart post request, but I'm new to requests.py and to programmatic file uploads.
Best Answer
You were very close! This was quite tricky actually as the ArcGIS REST API documentation didn't explain much. According to the requests docs, you can explicitly set the content headers. This worked for me:
The real magic happens right here, which is what the REST API is looking for:
And the Fiddler response/webform:
Also, I have just added this functionality to my restapi repository on GitHub. You can download this and use it to perform all kinds of operations against REST Services.
If you want to go this route, you can add attachments like this: