Upload attachments using clickup api - python-3.x

I'm trying to upload the attachments to a task on clickup.
Clickup API
Click up does provide example code the below is clickup example code
from urllib2 import Request, urlopen
values = """
attachment: raw_image_file (file)
filename: example.png (string)"""
headers = {
'Authorization': '\'access_token\'',
'Content-Type': 'multipart/form-data'
}
request = Request('https://private-anon-f799579c66-clickup20.apiary-mock.com/api/v2/task/{task_id}/attachment?custom_task_ids=&team_id=
', data=values, headers=headers)
response_body = urlopen(request).read()
print response_body
I used it as reference and used requests lib for the project
Here's the code using request lib
import requests
attachment_headers = {'Authorization': self.access_token, 'Content-Type': 'multipart/form-data'}
r = requests.post(f"https://private-anon-df9b125a00-clickup20.apiary-mock.com/api/v2/task/{task_id}/attachment",
files={"attachment": ("attachment", open("attachment.png", "rb")), "filename": "example.png"},
headers=attachment_headers)
print(r)
print(r.json())
I do get the status code as 200 and no error message but when I check on clickup task it doesn't show any attachments
Thanks for the help in advance!

You must remove the 'filename' part of your files param.
file = {"attachment": ('choose_your_name.png', open('file.png', 'rb'))}
headers = {'Authorization': config.clickup_access_token}
request = requests.post(f'https://api.clickup.com/api/v2/task/{task_id}/attachment', files=file, headers=headers)
print(request.json())

Related

Cloud Functions with Requests return 'Could not parse JSON' error

I'm running a cloud function in python to return some data from an api. The function is not executed and I have the error {'code': 400, 'message': 'Could not parse JSON'}.
Here is my code:
import requests
import json
def my_function(request):
url = 'https://blablabla/detailed'
headers = {'X-Api-Key': 'XXXXXXXX',
'content-type': 'application/json'}
data = '{"dateRangeStart":"2020-05-10T00:00:00.000","dateRangeEnd":"2020-05-16T23:59:59.000","amountShown": "HIDE_AMOUNT","detailedFilter":{ "page":"1","pageSize":"50"}}'
#req = requests.post(url, headers=headers, json=data)
req = requests.post(url, headers=headers, data=json.dumps(data))
print(req.json())
how should I format my data variable?
Just give your dict as your json argument, you don't need to specify the content-type headers requests will do it for you.
import requests
def my_function(request):
url = 'https://blablabla/detailed'
headers = {'X-Api-Key': 'XXXXXXXX', }
data = {"dateRangeStart": "2020-05-10T00:00:00.000", "dateRangeEnd": "2020-05-16T23:59:59.000", "amountShown": "HIDE_AMOUNT", "detailedFilter": { "page": "1", "pageSize": "50", }, }
req = requests.post(url, headers=headers, json=data)
print(req.json())
If you do not set a content-type header will try to set it for you:
When using the keyword argument json: it will set it to application/json
When using the keyword argument data (and the value passed respects some criteria, most of the time you don't have to worry about it): it will set it to application/x-www-form-urlencoded
If both kwargs are present data takes priority for the header so it will be set to application/x-www-form-urlencoded
I have not detailed the behaviour when the kwarg files is used as it would be really lengthy and is out of scope here.
Here's the source code.

Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile

Running a Django App locally, i can use Postman to upload a zip file along with some dict data. Breaking the application in 'def Post()' i can see that Postman's successful upload:
request.data = <QueryDict: {'request_id': ['44'], 'status': [' Ready For Review'], 'is_analyzed': ['True'], 'project': ['test value'], 'plate': ['Plate_R0'], 'antigen': ['tuna'], 'experiment_type': ['test'], 'raw_file': [<TemporaryUploadedFile: testfile.zip (application/zip)>]}>
Postman offers the following python code to replicate these results in my python script:
import requests
url = "http://127.0.0.1:8000/api/upload/"
payload = {'request_id': '44',
'status': ' Ready For Review',
'is_analyzed': 'True',
'project': 'test value',
'plate': 'Plate_R0',
'antigen': 'tuna',
'experiment_type': 'test'}
files = [
('raw_file', open(r'C:/testfile.zip','rb'))
]
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
running this code directly and retrieving the request.data (server side) i see the binary representation of the xlsx file is in the object and the payload data is not there (this is the error in the response).
How do i get my python script to produce the same server-side object as postman? Specifically how do i upload my data such that the file is represented as: <TemporaryUploadedFile: testfile.zip (application/zip)>
Thanks.
Turns out, inspection of the object posted by Postman shows that it was using multipart-form upload. Searching around i found this answer to a related question to describe posting as multi-part: https://stackoverflow.com/a/50595768/2917170 .
The working python is as follows:
from requests_toolbelt import MultipartEncoder
url = "http://127.0.0.1:8000/api/upload/"
zip_file = r'C:/testfile.zip'
m = MultipartEncoder([('raw_file', (os.path.basename(zip_file), open(zip_file, 'rb'))),
('request_id', '44'),
('status', 'Ready For Review'),
('is_analyzed', 'True'),
('project', 'test value'),
('plate', 'Plate_R0'),
('antigen', 'tuna'),
('experiment_type', 'test')])
header = {'content-type': m.content_type}
response = requests.post(url, headers=header, data=m, verify=True)

python requests getting unauthenticated or error 401

I'm trying to request post to my web server a notification but it shows error 401.
I already tested my API key in postman and it works but when I used it in python it shows error 401 or error:unathenticated.
Here's my code
import requests
req = requests.post('https://sampleweb.com/api/v1/devices/1/notifications',
json={ 'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9',
"notification": { "message":"hey", "level": 4}})
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
I've searched and read some documentations regarding to my question and I already solved it. Here's the code.
import requests
url = "https://sampleweb.com/api/v1/devices/1/notifications"
auth = {'Authorization': 'Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ',
'content-type':'application/json'}
params = {"notification":{"message":message,"level":level}}
req = requests.post(url, headers= auth, json = params)
print(req.json())
file = open("alert_content.txt", "a")
file.write(req.text + "\n")
file.close()
The authorization needs the content-type and the params or parameters needed to be in json format. Now it works.

upload file with post params

I want send file to url with some post params like "chat_id", "caption" and file must be sended as 'photo' field-name.
but I found only methods to send only POST params without file or sending only file without POST params and custom file name param..
This code send only params field, but I need also files field.
from urllib import parse, request
...
files={'photo': open('file.jpg','rb')}
params = parse.urlencode({'chat_id': chat_id, 'caption': 'test'})
#headers = {"Content-type": "multipart/form-data"}
req = request.Request(url, params.encode('ascii'))
response = request.urlopen(req)
print(response.read())
Python 3.4.2
ok. I found solution.
I install external lib Requests: HTTP for Humans.
and now i'm using requests
import requests
...
url = 'https://api.telegram.org/bot'+self.token+'/sendPhoto' #'/sendmessage'
print('request to '+url+' with params '+chat_id+' ' + text)
headers = {'Content-Type': 'multipart/form-data'}
files = {'photo': open('file.jpg', 'rb')}
params = {'chat_id': chat_id, 'caption': text}
r = requests.post(url, files=files, params=params)
print(r.text)

issue with aiohttp POST for a binary file upload

I have successfully used the requests module to upload a binary file (jpg), with something like the following:
upload_url = 'http:10.1.1.1:8080/api/media/photo'
headers = {'Authorization': token_string, 'Content-Type': 'image/jpg'}
data = open('photo.JPG', 'rb')
params = {'name': 'photo.JPG'}
r = requests.post(upload_url, params=params, data=data, headers=headers)
Now trying to do this with aiohttp client. This is what I have so far:
def upload_photos(token):
upload_url = '10.0.1.1:8080/api/media/photo'
headers = {'Authorization': token, 'Content-Type': 'image/jpg'}
data = {'file': open('photo.JPG', 'rb')}
params = {'name': 'photo.JPG'}
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(upload_photos(token))
But I am getting a 400 back, with {"detail": "Specified value is invalid: Invalid Content-Length specified"}.
It's as if it's not properly sending the photo.jpg. The aiohttp docs mentione multi-part encoded files and streaming, but that's not whant I want here.
How do I form a similar POST w/ binary file like in requests, but with aiohttp?
Thank you for a bug report. As workaround I guess to use chunked transfer encoding:
headers['Transfer-Encoding'] = 'chunked'
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers, chunked=1024)
The recipe should work, at least we have very simular code in our test suite: https://github.com/KeepSafe/aiohttp/blob/master/tests/test_client_functional.py#L322
I'll try to fix Content-Length calculation for your uploading way in next aiohttp release.

Resources