to generate client code from httpsnippet(npm) - npm

I am not able to get headers in the output while generating the client code
const snippet = new HTTPSnippet({
method: 'GET',
url: 'http://mockbin.com/request',
headers: {
'content-type': 'Application/json',
}
});
const options = { indent: '\t' };
const output = snippet.convert('shell', 'curl', options);
console.log(output);
output
[Error [HARError]: validation failed] {
errors: [
{
keyword: 'type',
dataPath: '.headers',
schemaPath: '#/properties/headers/type',
params: { type: 'array' },
message: 'should be array'
}
]
}
expected: - headers should be the part of the curl rather than this error

The validation message says that headers should be an array.
HAR Docs (found in httpsnippet);
<headers>
This object contains list of all headers (used in <request> and <response> objects).
"headers": [
{
"name": "Accept-Encoding",
"value": "gzip,deflate",
"comment": ""
},
{
"name": "Accept-Language",
"value": "en-us,en;q=0.5",
"comment": ""
}
]

Related

Sending attribute from Request JSON in Response JSON is not working in Wiremock

I am working on wiremock POC and I am facing issues when I try to send an attribute from request payload in response payload.
Request Payload:
{
"work_order": "12345678"
}
Mapping file:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{
"randomInteger": "d24ea3bf-36c0-40b8-b84b-b9268ee85f55",
"CorrelationID": "{
"work_order": "12345678"
}"
}
Above is working fine.
Now if I try to select the attribute value instead of entire body file, it is not working.
Mapping File:
{
"request": {
"method": "POST",
"urlPath": "/transform"
},
"response": {
"status": 200,
"body": "{\"randomInteger\": \"{{randomValue type = 'UUID'}}\",\"CorrelationID\": \"{{{request.body.work_order}}}\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}
Response Payload:
{"randomInteger": "e35e4d5f-b043-4770-b659-4131d313e002","CorrelationID": ""}

React native sending image to server using formdata

I have a problem sending a picture to a server, that's like the default approach, but it does not seem to work.
var source = '/Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
const form = new FormData();
form.append('image', {
uri: source,
type: 'image/jpg',
name: '123.jpg',
});
const data = () => {
fetch(api ,{
method: 'POST',
body: form,
})
that's the response i get from the server:
{
"_bodyBlob": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"_bodyInit": {
"_data": {
"__collector": [
Object
],
"blobId": "78B18938-15BF-4F18-B3C8-1EB30A24D9F8",
"name": "test.html",
"offset": 0,
"size": 192,
"type": "text/html"
}
},
"bodyUsed": false,
"headers": {
"map": {
"connection": "keep-alive",
"content-length": "192",
"content-type": "text/html",
"date": "Mon, 02 Nov 2020 22:57:21 GMT",
"server": "PythonAnywhere"
}
},
"ok": false,
"status": 400,
"statusText": undefined,
"type": "default",
"url": api
}
Although this python code works perfectly and gets a correct response
img = {'file':('123.png', open('the path to the pic/123.png', 'rb'), 'image/png)}
post(api, files = img)
is there any way to get this working or its the server side problem that can't receive the correct arguments?
Adding "file://" to the beginning of the source string fixed the problem.
so the src looks like
var source = 'file:///Users/alexx/Library/Developer/CoreSimulator/Devices/44F0FA92-4898-4CFB-862E-4E5EC4C8AB28/data/Containers/Bundle/Application/34BCE695-4B4F-472F-AB5C-F2336AC45273/DoorLock.app/123.jpg';
then it fetches perfectly, hope it helps anybody who tries to send a local image using formdata, the summary looks like this now
const form = new FormData();
form.append('file', {
uri: source,
name: '123.jpg',
fileName: 'file', //optional
});
fetch(uri,{
method: 'post',
body: form,
})
.then(response => {
console.log("image uploaded")
console.log(response)
})
.catch(console.log);
In Formdata when you pass files, you need to pass 3 parameters where
key expected from the backend (in your case image).
It will be an object which has three properties named name, type, and uri where type is the mime type (ex: image/jpeg).
name of the file
Eg:
data.append("FilePath",{
name:"image.png",
type:"image/png",
uri:"content://com.camera/image.png"
},image.png)

Receiving [object object] from API

I tried for hours but could not extract the object value
when I execute api in postman tool I received successful message:
[
{
"Name": "Raj",
"City": "HYD",
"Initial": "SSS"
},
{
"Name": "JOHN",
"City": "HYD",
"Initial": "SSS"
},
{
"Name": "Rakesh",
"City": "HYD",
"Initial": "SSS"
}
]
But when I am trying to access same from React native but it is showing me [object object]. How to extract Name field from it?
script:
fetch('http://190.1.120.198:3538/CustomerList/api/userList', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username:'John',
password:'UZ4952!',
Organization:'NZE'
}),
}).then((response) => response.json())
.then((responseJson) => {
console.log("myMessage:"+responseJson);
})
.catch((error) => {
console.error(error);
});
It is because you are trying to print the responseJson in logs by concatenating it with a string. When you add an object to string it will always print [object object].
console.log("myMessage:"+responseJson);
Output:
myMessage:[object object]
If you want to print the exact value of your json response you can do that in these two ways:
console.log("myMessage:",responseJson);
console.log("myMessage:"+JSON.stringify(responseJson));

React Native use Twitter search API with Application-only authentication

I am new to React Native and want to build an App that uses the Twitter search API to display Tweets. No need for User Authentication.
I've been struggling the last two nights to get this working and starting to get frustrated xD.
I've tried building the request using Fetch and XMLHttpRequest with no luck. Also I tried several packages enabling OAuth 2.0 which also didn't work. I have the feeling I'm over complicating things as all I want to do is use the Application-only authentication and use the Standard search API.
Does anyone out there please have a code snippet on how to do this in react native without any extra packages? Is it possible at all with "just" Fetch or XMLHttpRequest?
Thanks in advance
Edit: Here's my code so far
var base64 = require('base-64');
var credentials = encodeURIComponent(key) + ":" + encodeURIComponent(secret);
var encoded = new Buffer(credentials).toString('base64');
console.log(encoded);
fetch('https://api.twitter.com/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + encoded
},
body: {
'grant_type': 'client_credentials'
},
}).then((response) => console.log(response))
Here the response:
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "8dea4e53-7b39-4b78-b1a5-d7ef5a58de48",
"offset": 0,
"size": 114,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "8dea4e53-7b39-4b78-b1a5-d7ef5a58de48",
"offset": 0,
"size": 114,
},
},
"headers": Headers {
"map": Object {
"cache-control": Array [
"public, max-age=0",
],
"content-disposition": Array [
"attachment; filename=json.json",
],
"content-type": Array [
"application/json;charset=utf-8",
],
"date": Array [
"Wed, 16 May 2018 16:55:48 GMT",
],
"expires": Array [
"Tue, 31 Mar 1981 05:00:00 GMT",
],
"last-modified": Array [
"Wed, 16 May 2018 16:55:48 GMT",
],
"ml": Array [
"A",
],
"server": Array [
"tsa_o",
],
"status": Array [
"403 Forbidden",
],
"strict-transport-security": Array [
"max-age=631138519",
],
"x-connection-hash": Array [
"b6dde5b876b934c8dcdb059ef0c400fa",
],
"x-content-type-options": Array [
"nosniff",
],
"x-frame-options": Array [
"DENY",
],
"x-response-time": Array [
"105",
],
"x-transaction": Array [
"0084737c0054c4dc",
],
"x-tsa-request-body-time": Array [
"26",
],
"x-twitter-response-tags": Array [
"BouncerCompliant",
],
"x-ua-compatible": Array [
"IE=edge,chrome=1",
],
"x-xss-protection": Array [
"1; mode=block; report=https://twitter.com/i/xss_report",
],
},
},
"ok": false,
"status": 403,
"statusText": undefined,
"type": "default",
"url": "https://api.twitter.com/oauth2/token",
}
So, I'm happy to report I got this working.
Main problem was the encoding of the Request Body.
Here"s the working code to authenticate and get a bearer token. Then using this token to use the search API:
_getBearer = () => {
var details = {
'grant_type': 'client_credentials'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
var key = "xxx";
var secret = "yyy";
var base64 = require('base-64');
var credentials = encodeURIComponent(key) + ":" + encodeURIComponent(secret);
var encoded = new Buffer(credentials).toString('base64');
console.log("Created encoded credentials: " + encoded);
fetch('https://api.twitter.com/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + encoded
},
body: formBody
}).then((response) => response.json())
.then((responseData) => {
bearerToken = responseData.access_token;
console.log("Got Bearer: " + responseData.access_token);
this._loadTweet();
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
_loadTweet = () => {
console.log("start load tweet");
fetch('https://api.twitter.com/1.1/search/tweets.json?q=love', {
method: 'GET',
headers: {
'Authorization': "Bearer " + bearerToken
}
}).then((response) => response.json())
.then((responseData) => {
console.log(JSON.stringify(responseData));
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
};
};

How to create a webhook on a repository on the GitHub web api using AJAX?

I am experimenting with Webhooks in the GitHub api. I got one working by doing it manually as in going into my repository and clicking into the setting and enabling a web hook. But now I want to do this in AJAX and I am getting problems. Anytime I try to send a POST to the web api it fails with a 400 (Bad Request). I am not sure where I am going wrong with my code.
function createWebHooksOnRepos(token){
const webhookURL = "https://api.github.com/repos/DanoBuck/AlgorithmsAndDataStructures/hooks";
const json = {
"name": "WebHook",
"active": true,
"events": [
"issue_comment",
"issues"
],
"config": {
"url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
"content_type": "json"
}
};
$.ajax({
headers: {
"Authorization": "Token " + token
},
url: webhookURL,
data: json,
type: "POST",
dataType: "json",
success: function(data){
console.log(data);
}
});
}
Thank you
From github Webhook API doc :
name - string - Required. Use "web" for a webhook or use the name of a valid
service. (See /hooks for the list of valid service names.)
So in your case, just rename Webhook to web :
const json = {
"name": "web",
"active": true,
"events": [
"issue_comment",
"issues"
],
"config": {
"url": "http://39a40427.ngrok.io/api/webhooks/incoming/github",
"content_type": "json"
}
};
Also JSON.stringify your data before sending :
$.ajax({
headers: {
"Authorization": "Token " + token
},
url: webhookURL,
data: JSON.stringify(json),
type: "POST",
dataType: "json",
success: function(data) {
console.log(data);
}
});