i'm trying to convert my curl to a python code, unfortunately without any success.
can anyone help me with this one, please?
curl -k -X "POST" "https://192.168.16.220:9000/api/views/search/messages" \
-H 'X-Requested-By: superman' \
-H 'Content-Type: application/json' \
-H 'Accept: text/csv' \
-u 'admin:admin' \
-d $'{
"streams": [
"62948e1fcd664d57cccfa29c"
],
"query_string": {
"type": "elasticsearch",
"query_string": "source"
},
"timerange": {
"type": "relative",
"range": 30
}
}'
This should work, also I suggest using this handy site in the future
import requests
headers = {
'X-Requested-By': 'superman',
# Already added when you pass json= but not when you pass data=
# 'Content-Type': 'application/json',
'Accept': 'text/csv',
}
json_data = {
'streams': [
'62948e1fcd664d57cccfa29c',
],
'query_string': {
'type': 'elasticsearch',
'query_string': 'source',
},
'timerange': {
'type': 'relative',
'range': 30,
},
}
response = requests.post('https://192.168.16.220:9000/api/views/search/messages', headers=headers, json=json_data, verify=False, auth=('admin', 'admin'))
# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
#data = '{\n "streams": [\n "62948e1fcd664d57cccfa29c"\n ],\n "query_string": {\n "type": "elasticsearch",\n "query_string": "source"\n },\n "timerange": {\n "type": "relative",\n "range": 30\n }\n}'
#response = requests.post('https://192.168.16.220:9000/api/views/search/messages', headers=headers, data=data, verify=False, auth=('admin', 'admin'))
get the data from the api like this for json data
json_data = response.json()
or get the data from the api like this for text data
json_data = response.text
Related
I want to create a mitm proxy that can only be access by providing correct credentials:
(async () => {
const mockttp = require('mockttp');
// Create a proxy server with a self-signed HTTPS CA certificate:
const https = await mockttp.generateCACertificate();
const server = mockttp.getLocal({ https });
// Inject 'Hello world' responses for all requests
// Replace targets entirely with custom logic:
let counter = 0;
server.forAnyRequest().thenCallback((request) => {
console.log(JSON.stringify(request));
return {
status: 200,
// Return a JSON response with an incrementing counter:
json: { counterValue: counter++ }
};
});
await server.start(8080);
// Print out the server details:
const caFingerprint = mockttp.generateSPKIFingerprint(https.cert)
console.log(`Server running on port ${server.port}`);
console.log(`CA cert fingerprint ${caFingerprint}`);
})(); // (Run in an async wrapper so we can use top-level await everywhere)
With http it works flawlessly, the proxy-authorization header is present:
curl -k -v --proxy "user:pass#127.0.0.1:8080" http://www.google.com
{
"id":"8978f1a3-8a4f-4395-b0dc-0cf8929e760a",
"matchedRuleId":"5a1bc167-7e34-4b0d-9f51-f8e49015b349",
"protocol":"http",
"httpVersion":"1.1",
"method":"GET",
"url":"http://www.google.com/",
"path":"/",
"remoteIpAddress":"::ffff:127.0.0.1",
"remotePort":32932,
"headers":{
"host":"www.google.com",
"proxy-authorization":"Basic dXNlcjpwYXNz",
"user-agent":"curl/7.83.1",
"accept":"*/*",
"proxy-connection":"Keep-Alive"
},
"rawHeaders":[
[
"Host",
"www.google.com"
],
[
"Proxy-Authorization",
"Basic dXNlcjpwYXNz"
],
[
"User-Agent",
"curl/7.83.1"
],
[
"Accept",
"*/*"
],
[
"Proxy-Connection",
"Keep-Alive"
]
],
"tags":[
],
"timingEvents":{
"startTime":1663860475270,
"startTimestamp":7655.8840999901295,
"bodyReceivedTimestamp":7656.588100001216
},
"body":{
"buffer":{
"type":"Buffer",
"data":[
]
}
}
}
Now the problem is that if it runs through https, the proxy-authorization disappears:
curl -k -v --proxy "user:pass#127.0.0.1:8080" https://www.google.com
{
"id":"dd9f61c9-8ecb-4f94-87aa-095fd2f40da6",
"matchedRuleId":"5a1bc167-7e34-4b0d-9f51-f8e49015b349",
"protocol":"https",
"httpVersion":"1.1",
"method":"GET",
"url":"https://www.google.com/",
"path":"/",
"remoteIpAddress":"::ffff:127.0.0.1",
"remotePort":34557,
"headers":{
"host":"www.google.com",
"user-agent":"curl/7.83.1",
"accept":"*/*"
},
"rawHeaders":[
[
"Host",
"www.google.com"
],
[
"User-Agent",
"curl/7.83.1"
],
[
"Accept",
"*/*"
]
],
"tags":[
],
"timingEvents":{
"startTime":1663860737403,
"startTimestamp":269786.7910999954,
"bodyReceivedTimestamp":269787.29159998894
},
"body":{
"buffer":{
"type":"Buffer",
"data":[
]
}
}
}
Is there anything I'm unaware of that causes this behaviour?
My objective is to post a message on personalChat in msteamsbot using restapi endpoint.
auth token is generated using below logic (reference doc)
let url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token";
const data = {
'grant_type': 'client_credentials',
'client_id' : '...',
'client_secret' : '...',
'scope' : 'https://api.botframework.com/.default'
};
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
the token generated using above logic is passed to below api (reference doc). This api is supposed to post a message on the recipient's chat. but this doesn't happen.
curl --location --request POST 'https://smba.trafficmanager.net/apis/v3/conversations/a:1NYEIhjRpL_RgDBDaA7lJyO6kl8rbpWQLyKkayQnZ_mKOZhnKAoeuiWEekt8vpjeoIcB3R394k6-zeC52sk60Q8ErZO5PIokS8ytjD-QK-CIJjIRaGg94KzTMz2d3XXjs/activities' \
--header 'Authorization: Bearer authToken' \
--header 'Content-Type: application/json' \
--data-raw '{
"type": "message",
"recipient": {
"id":"29:1dePA4jI3vyrUt-38_--KJxVeAg_v-XQVCBHcSxp4kgu7ZshPPSbsbSOZ7m-GAKK0IARbqyxg_bit-IAt0J9d_w"
},
"from": {
"id": "28:f4016730-f1ef-4fcd-9169-4159a2295591",
"name": "Toolkit Bot - vTAPBotdemo"
},
"channelData": {
"notification": {
"alert": "true"
}
},
"text": "Hello "
}'
Below is the error message i receive when triggering the above api.
Please let me know how to resolve this issue
The endpoint i used to postMessage on personal chat is incorrect and it was present in the docs as well.
Below is the correct endpoint. This endpoint can be seen by logging the http payload request body of /api/messages api
curl --location --request POST 'https://smba.trafficmanager.net/amer/v3/conversations/{conversationid}/activities/{activityid}' \
--header 'Authorization: Bearer authToken' \
--header 'Content-Type: application/json' \
--data-raw '{
"type": "message",
"recipient": {
"id":"29:1dePA4jI3vyrUt-38_--VeAgKJx_v-CBHXQVcSxp4kgu7ZshPPSbsbSOZ7m-GAKK0IARbqyxg_bit-IAt0J9d_w"
},
"from": {
"id": "28:f4016730-f1ef-4fcd-9169-4159a2295591",
"name": "Toolkit Bot - vTAPBotdemo"
},
"channelData": {
"notification": {
"alert": "true"
}
},
"text": "Hello "
}'
i would like to replicate all design docs and some docs that contain field clientId from orginal (A) to replication (B).
i have tried 2 ways but bothe have the same problem:
it updates my design docs continuously but not the normal docs with clientId. they only replicate one time on creation of replication.
1. try
curl -H 'Content-Type: application/json' \
-X POST http://admin:*******#mycare.owitec.lan:5984/_replicator \
-d '{
"continuous" : true,
"create_target" : true,
"source" : {
"url": "http://mycare.owitec.lan:5984/mycare_10001",
"headers": {
"Authorization": "Basic YWRtaW46QXNkZmdoKjU9"
}
},
"target" : {
"url": "http://mycare.owitec.lan:5984/mycare_rep_10001",
"headers": {
"Authorization": "Basic YWRtaW46QXNkZmdoKjU9"
}
},
"filter": "article/clientDataRep"
}'
function(doc, req) {
var v = doc._id.substr(0, 6);
if (v === '_desig' || v === '10001:') {
return true;
}
return false;
}
2. try
curl -H 'Content-Type: application/json' \
-X POST http://admin:********#mycare.owitec.lan:5984/_replicator \
-d '{
"continuous" : true,
"create_target" : true,
"source" : {
"url": "http://mycare.owitec.lan:5984/mycare_10001",
"headers": {
"Authorization": "Basic YWRtaW46QXNkZmdoKjU9"
}
},
"target" : {
"url": "http://mycare.owitec.lan:5984/mycare2_rep_10001",
"headers": {
"Authorization": "Basic YWRtaW46QXNkZmdoKjU9"
}
},
"selector": { "clientId": {"$exists": false} }
}'
i also checked both dbs for conflicts and there are none in both. what am i doing wrong? in other dbs where i have both-way-replication (from/to) i have no problems!
it was the validate_doc_update function of a design document that checked 2 things:
if it is a update then you have to be the author or have a certain rule
according to doc.type object was only allowed certain fields and i had old data that didnt conform
the replication was always running i just didnt notice (think about) that the validate_doc_update was filtering it
Below you can see the json object It has image field.I want to grab the image from that field and pass it to form-data and afterwards I want to pass that form-data to carry out post request via Axios.The post request accept multipart/form-data as a header and a token for authentication and form-data as data .
{
"id": 4,
"title": "myProduct ",
"description": "",
"price": "64/Kg",
"subcode": "subcode1",
"status": "active",
"user_id": 4,
"category_id": 1,
"slug": "anything",
"created_at": "2019-01-03 20:30",
"updated_at": "2019-06-11 11:49",
"gst": 5,
"vendor_id": 1,
"rank": null,
"fresh": 0,
"delivery_id": 1,
"buffer_time": 12,
"discount": null,
"subscribed": null,
"subcategory_id": null,
"commission": null,
"images": [
{
"id": 137,
"src": "https://anything/1547719669239.jpeg",
"product_id": 4
}
]
}
This is how i have to make request i am getting error status 422 UNPROCESSABLE ENTITY please look into it
curl -i -X POST
-H "X-Token: USER_TOKEN"
-H "Content-Type: multipart/form-data"
-F "image[attachment]=#/absolute/path/to/image.jpg"
-F "type=image/jpeg"
https://localhost:3000/anything/images
Code that I tried is below
app.post("/images",async(req,res)=>{
try{
var formData = new FormData();
formData.append("image[attachment]",items[4].images[0].src,{type:"image/jpeg"});
const headers = {
"Content-Type" :"multipart/form-data",
}
let resp = await axios.post(" https://localhost:3000/anything/images",formData,{
headers:headers,
params:{
token:"mytoken"
},
})
console.log(resp.status);
return;
}catch(err){
console.log(err);
}
res.send("Outside"
); })
Let say, the object name here is Obj, then you can access the images src by
Obj.images[0].src
This is you can proceed:
let formData = new FormData();
formData.append('file', Obj.images[0].src);
this.$axios.post('/v1/candidate/attachment',formData)
.then((objResponse) => {
},
(objError) => {
});
I solved this issue by first downloading the image to my local system and passing it like
data.append('image[attachment]', fs.createReadStream('/home/images/riceBasm.jpeg'));
As the request work with postman so I checked the code section of postman and I found this piece of code over there . So do check the postman code section if you get stucked and the request is working with postman but fails for your code.
Dead simple search query only using required fields:
{ schema_id: 'xxxxxxxx-8b39-427a-8fb8-c764957fd9c6',
filter: { last_name: { type: 'not', value: 'Smith' } } }
POSTing to https://api.truevault.com/v1/vaults/xxxxxxxx-15e3-442e-aa6f-xxxxxxxx/search
When POSTing, the POST call options look like this:
{
data: { search_option: 'xxxx base64 encoded JSON.stringify of the above xxxxxxx' },
headers: { Authorization: 'Basic xxx base64 encoded API KEY xxx' }
}
Authorization is working. Result:
{ Error: failed [400] { "error": { "code":
"SEARCH.INVALID_SEARCH_QUERY", "message": "Invalid
search_option.", "type": "invalid_request_error" },
"result": "error", "transaction_id":
"9ad83046-1906-406c-87ab-963b904857c4" }
curl command for the same search query:
curl -d "{ search_option: 'eyJzY2hlbWFfaWQiOiJlOWVmYmE0NC04YjMwLTQyN2EtOGZiOC1jNzY0OTU3ZmMwZGUiLCJmaWx0ZXIiOnsibGFzdF9uYW1lIjp7InR5cGUiOiJ3aWxkY2FyZCIsInZhbHVlIjoiRnJhbnptZWllcioifX19' }"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=="
https://api.truevault.com/v1/vaults/xxxxxxxx-15e3-442e-aa6f-4xxxxxxxxxx/search
Same error:
{
"error": {
"code": "SEARCH.INVALID_SEARCH_QUERY",
"message": "Invalid search_option.",
"type": "invalid_request_error"
},
"result": "error",
"transaction_id": "b5a51185-264f-4765-a1b8-6ae9e491aa39"
}
Alex,
I don't think your curl command is formatted the way TrueVault expects. This may also be your problem in your http library. The curl command I'd expect is:
curl https://api.truevault.com/v1/vaults/xyz/search \
-XPOST \
-H "Content..."
-H "Auth..."
-d "search_option=eyJ...."
That is, the data payload is form-encoded (param1=value1¶m2=value2) not JSON.
It looks like the docs for search were missing a sample curl, but you can see a similar curl for document create listed in the docs.
I ran into I believe the same issue in my juery ajax request. For me, it was that I was sending my request with header{'Content-Type':'application/json'}, but it needs to be form-data.
Working example:
var api_url = 'https://api.truevault.com/v1/vaults/' + vault_id + '/search';
var data = {
'schema_id' : schema_id,
'page' : 1,
'per_page' : 50,
'filter_type' : 'and',
'full_document' : false,
"sort": [
{
"SomeField":"asc"
}
],
'filter':{
'SomeField':{
'type':'eq',
'value': somevalue
}
}
};
data = btoa( JSON.stringify( data ) );
$.ajax({
type : 'POST',
url : api_url,
dataType : 'json',
processData : false,
headers : {
'Authorization':'Basic '+ btoa( auth_key+":" ),
},
mimeType : "multipart/form-data",
data : 'search_option='+ data,
error: function( response ) {
//
},
success: function( response ) {
//
}
});