How to give Form-param, both values and files in a http request in python - python-3.x

I wanna make a http request as shown in the below curl command:
curl -X PUT \
https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles \
-H 'authorization: Bearer XXX' \
-H 'cache-control: no-cache' \
-H 'content-length: 0' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-H 'host: anypoint.mulesoft.com' \
-H 'postman-token: XXX' \
-H 'x-anypnt-env-id: XXX' \
-H 'x-anypnt-org-id: XXX' \
-F 'appInfoJson={
"muleVersion": {
"version": "3.8.5"
},
"properties":{"env":"dev"}
}'
I have tried the below request but all vain
files = {'file': open('C:\Users\\highfiles.zip', 'rb')}
appInfoJson1 = {
"muleVersion": {
"version": "3.8.5"
},
"properties": {"env":"dev1"}
}
print dict(appInfoJson=appInfoJson1)
headers = {"X-ANYPNT-ORG-ID": "XXXX",
"X-ANYPNT-ENV-ID": "XXXX",
"Authorization": "Bearer " + access_token,
}
response = requests.put("https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles",
data=dict(appInfoJson=appInfoJson1) , files=files, headers = headers)
How do I give a form-Param values and file in a python http request.

I was doing it wrong.
The change was only w.r.t handling the dict values, shown below:
response = requests.put("https://anypoint.mulesoft.com/cloudhub/api/v2/applications/highfiles",
data=dict(appInfoJson=appInfoJson1.values()) , files=files, headers = headers)

Related

How to delay curl request

I'd like to add sleep to this request so as not to stress the server with too many requests at a go. I've tried adding sleep but I don't get the expected behaviour. The help is appreciated.
xargs -I{} curl --location --request POST 'https://g.com' \
--header 'Authorization: Bearer cc' \
--header 'Content-Type: application/json' \
--data-raw '{
"c_ids": [
"{}"
]
}' '; sleep 5m' < ~/recent.txt
Escaping arbitrary strings into valid JSON is a job for jq.
If you don't have a particular reason to define the curl args outside your loop:
while IFS= read -r json; do
curl \
--location --request POST 'https://g.com' \
--header 'Authorization: Bearer cc' \
--header 'Content-Type: application/json' \
--data-raw "$json"
sleep 5m
done < <(jq -Rc '{"c_ids": [ . ]}' recent.txt)
...or if you do:
curl_args=(
--location --request POST 'https://g.com' \
--header 'Authorization: Bearer cc' \
--header 'Content-Type: application/json' \
)
while IFS= read -r json; do
curl "${curl_args[#]}" --data-raw "$json"
sleep 5m
done < <(jq -Rc '{"c_ids": [ . ]}' recent.txt)
Putting the sleep in the xargs is a bit wonky. I advise the following approach which is more likely to supply the desired result.
#!/bin/sh
siteCommon="--location --request POST 'https://g.com' \
--header 'Authorization: Bearer cc' \
--header 'Content-Type: application/json' "
while read -r line
do
eval curl ${siteCommon} --data-raw \'{ \"c_ids\": [ \"${line}\" ] }\'
sleep 5m
done < ~/recent.txt

How to send curl request with post data imported from a file

I have a curl command like below which works fine and I get the response back. I am posting json data to an endpoint which gives me response back after hitting it.
curl -v 'url' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: url' --data-binary '{"query":"\n{\n data(clientId: 1234, filters: [{key: \"o\", value: 100}], key: \"world\") {\n title\n type\n pottery {\n text\n pid\n href\n count\n resource\n }\n }\n}"}' --compressed
Now I am trying to read the binary data from temp.json file outside but somehow it doesn't work and I get an error -
curl -v 'url' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: url' --data-binary "#/Users/david/Downloads/temp.json" --compressed
I have stored json in below temp.json file -
{
data(clientId: 1234, filters: [{key: "o", value: 100}], key: "world") {
title
type
pottery {
text
pid
href
count
resource
}
}
}
This is the error I am getting -
.......
* upload completely sent off: 211 out of 211 bytes
< HTTP/1.1 500 Internal Server Error
< date: Fri, 28 May 2021 23:38:12 GMT
< server: envoy
< content-length: 0
< x-envoy-upstream-service-time: 1
<
* Connection #0 to host url left intact
* Closing connection 0
Is there anything wrong in my above curl command?
Update
If I copy the exact same content in the temp.json file that I have in my original curl with \n then it works fine. So looks like that is the issue.
It means I need to find a way to convert new lines to \n manually from temp.json before sending the curl request or is there any other way?

convert curl to python requests (pisignage API)

I am trying to convert a curl of pisignage into python requests. The curl is,
curl -X POST "https://swagger.piathome.com/api/files" -H "accept:
application/json" -H "x-access-token: login_session_token" -H
"Content-Type: multipart/form-data" -F "Upload
file=#test.jpg;type=image/jpeg"
My code is,
import requests
files = {'Upload file': open('test.jpg', 'rb'), 'type': 'image/jpeg'}
headers = {'Content-type': 'multipart/form-data', 'accept': 'application/json', 'x-access-token': 'login_session_token'}
file_response = requests.post(
'https://swagger.piathome.com/api/files',
files=files,
headers=headers
)
print(file_response)
It returns 404. I tried uncurl, the code is:
import uncurl
u = uncurl.parse('curl -X POST "https://swagger.piathome.com/api/files" -H "accept: application/json" -H "x-access-token: login_session_token" -H "Content-Type: multipart/form-data" -F "Upload file=test.jpg;type=image/jpeg"')
print(u)
The output is ,
error: unrecognized arguments: -F Upload file=test.jpg;type=image/jpeg
After a day of searching it turns out the swagger documentation is incorrect.
use
files = {
'assets': (open('test.jpg', 'rb'))
}
Try this
import requests
headers = {
'accept': 'application/json',
'x-access-token': 'login_session_token',
'Content-Type': 'multipart/form-data',
}
files = {
'Upload file': (None, 'test.jpg;type'),
}
response = requests.post('https://swagger.piathome.com/api/files', headers=headers, files=files)
link to parse curl to request python

Skype for Business in Azure UCWA authentication - Issued token not accepted

I am integrating Java application with Skype for Business in Azure using UCWA and here is the list of actions that I performed. When it seemed that everything is working and covered, I am stuck at unexpected place. Probably the solution is something trivial, like adding an addition permission, but I cannot find it. Also, I am sure that this post will help someone who is stuck in earlier stage.
Register application in Azure portal:
Register as Native application
Add required permissions to all Skype for Business Online Permissions
Grant permissions to all users
Get the app id (will use it later as client id)
HTTP Get, btw: (tenant) should be replaced with actual tenant name
Request:
curl -X GET \
http://lyncdiscover.(tenant).onmicrosoft.com/ \
-H 'cache-control: no-cache' \
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
-H 'postman-token: b45b8fee-852f-4678-3631-3a06727d99fc' \
-F Capture=undefined
Response:
`{
"_links": {
"self": {
"href": "https://webdir0a.online.lync.com/Autodiscover/AutodiscoverService.svc/root?originalDomain=(tenant).onmicrosoft.com"
},
"xframe": {
"href": "https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root/xframe"
},
"redirect": {
"href": "https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root?originalDomain=(tenant).onmicrosoft.com"
}
}
}`
HTTP Get redirect url
curl -X GET \
'https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root?originalDomain=(tenant).onmicrosoft.com' \
-H 'cache-control: no-cache' \
-H 'postman-token: 273cad2b-a9a9-9882-8634-b52f9a9976b5'
{
"_links": {
"self": {
"href": "https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root?originalDomain=(tenant).onmicrosoft.com"
},
"user": {
"href": "https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user?originalDomain=(tenant).onmicrosoft.com"
},
"xframe": {
"href": "https://webdir3a.online.lync.com/Autodiscover/XFrame/XFrame.html"
}
}
}
Get user url
curl -X GET \
'https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user?originalDomain=(tenant).onmicrosoft.com' \
-H 'cache-control: no-cache' \
-H 'postman-token: af9ab0bd-dc6f-b2f3-e7d9-23941aac5537'
response: 401 Unauthorized
Read response http header and extract
`authorization_uri="https://login.windows.net/common/oauth2/authorize"`
Post to authorization url:
client+id = app id from azure portal app registration
resource=00000004-0000-0ff1-ce00-000000000000 (SfB resource id)
curl -X POST \
https://login.windows.net/common/oauth2/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded;charset=UTF-8' \
-H 'postman-token: 39902b3f-00c3-e7a8-75d0-6b94f10e07ed' \
-d 'resource=00000004-0000-0ff1-ce00-000000000000&client_id=XXXX-XXXX-XXXX&grant_type=password&username=actualUserName#tenant.com&password=actual_password&scope=openid'
response:
`{
"token_type": "Bearer",
"scope": "Contacts.ReadWrite Conversations.Initiate Conversations.Receive Meetings.ReadWrite User.ReadWrite",
"expires_in": "3599",
"ext_expires_in": "0",
"expires_on": "1518196708",
"not_before": "1518192808",
"resource": "00000004-0000-0ff1-ce00-000000000000",
"access_token": "eyJ0...",
"refresh_token": "AQABA...",
"id_token": "eyJ0e..."
}`
Yes, I am getting actual token and everything seems to be fine, but it is not. When I use this token to get user url again the response now is 403 Forbidden and I am stuck.
`curl -X GET \
'https://webdir3a.online.lync.com/Autodiscover/AutodiscoverService.svc/root/oauth/user?originalDomain=(tenant).onmicrosoft.com' \
-H 'authorization: Bearer eyJ0eXA...' \
-H 'cache-control: no-cache' \
-H 'postman-token: ff0a80bd-5025-5b28-3f1c-cf9205890812'`
response: 403 Forbidden
` <body>
<div id="header">
<h1>Server Error</h1>
</div>
<div id="content">
<div class="content-container">
<fieldset>
<h2>403 - Forbidden: Access is denied.</h2>
<h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
</fieldset>
</div>
</div>
</body>`
The mistake is in step #4, parameter resource. Correct request uses user server url as resource parameter:
curl -X POST \
https://login.windows.net/common/oauth2/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded;charset=UTF-8' \
-H 'postman-token: 39902b3f-00c3-e7a8-75d0-6b94f10e07ed' \
-d 'resource=https://webdir3a.online.lync.com&client_id=XXXX-XXXX-XXXX&grant_type=password&username=actualUserName#tenant.com&password=actual_password&scope=openid
and then use received token to get the application url from user url.
Once application url is retrieved, a new token request must be posted to get token for application server, in my case that was:
curl -X POST \
https://login.windows.net/common/oauth2/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded;charset=UTF-8' \
-H 'postman-token: 39902b3f-00c3-e7a8-75d0-6b94f10e07ed' \
-d 'resource=https://webpoolsn23a14.infra.lync.com&client_id=XXXX-XXXX-XXXX&grant_type=password&username=actualUserName#tenant.com&password=actual_password&scope=openid
This token can finally be used to create an application and other messaging services.

Not Authorized to create vertexes in IBM Graph

Tried to enter vertexes:
curl -X 'POST' -d '{"vertexLables": [{"name": "event"},{"name": "category"}]}' -H 'content-type: application/json' -H 'authorization: gds-token yyyy https://ibmgraph-alpha.ng.bluemix.net/zzzz/g/schema
{"code":"NotAuthorized","message":""}

Resources