issues with fetching data from rapid API, using fetch-node - api

I've copied the demo code off their site but it seems that I can't crack it, I've never got this error, Used double quotes and without quotes on the keys in the post options, still getting this error.
const res = await fetch("https://textanalysis-keyword-extraction-v1.p.rapidapi.com/keyword-extractor-text", {
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"x-rapidapi-key": "ksjadkasjkasjkfjhjafkakjkajkasjf", // hidden key
"x-rapidapi-host": "textanalysis-keyword-extraction-v1.p.rapidapi.com"
},
"body": {
"text": "Keyword extraction is tasked with the automatic identification of terms that best describe the subject of a document. Key phrases, key terms, key segments or just keywords are the terminology which is used for defining the terms that represent the most relevant information contained in the document. Although the terminology is different, function is the same",
"wordnum": "5"
}
})
.then(response => {
console.log(response);
console.log(response.headers);
})
.catch(err => {
console.error(err);
});
Here is the error, apparently it's something to with "[Symbol(Body internals)]" coming out as an empty object
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://textanalysis-keyword-extraction-v1.p.rapidapi.com/keyword-extractor-text',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] }, // error code
counter: 0
}
}

Generally, a 404 code indicates malformed request syntax, invalid request message framing, or deceptive request routing.
But everything looks good in the code snippet that you have posted above. Try this:
fetch("https://textanalysis-keyword-extraction-v1.p.rapidapi.com/keyword-extractor-text", {
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"x-rapidapi-host": "textanalysis-keyword-extraction-v1.p.rapidapi.com",
"x-rapidapi-key": ""
},
"body": {
"wordnum": "5",
"text": ""
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
});
You can always get in touch with the support team at support#rapidapi.com

Related

to generate client code from httpsnippet(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": ""
}
]

React Native: Fetch Stripe API

I'm attempting to fetch() Stripe's API to create a payment token directly from the front-end with React Native.
I'm doing so with the following:
const genCard = {
'card[number]': "4242424242424242",
'card[exp_month]': "11",
'card[exp_year]': "25,
'card[cvc]': "111"
}
var formBody = []
for (var property in genCard) {
var encodedKey = encodeURIComponent(property)
var encodedValue = encodeURIComponent(genCard[property])
formBody.push(encodedKey + "=" + encodedValue)
}
formBody = formBody.join("&")
const result = fetch("https://api.stripe.com/v1/tokens", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer " + "sk_test_4eC39HqLyjWDarjtT1zdp7dc",
},
body: formBody
}).then(response => response.json())
console.log('logging: \n', genCard, '\n', formBody, '\n', result)
The logging output gives me the following:
logging:
{"card[cvc]": "111", "card[exp_month]": "11", "card[exp_year]": "25", "card[number]": "4242424242424242"}
card%5Bnumber%5D=4242424242424242&card%5Bexp_month%5D=11&card%5Bexp_year%5D=25&card%5Bcvc%5D=111
{"_40": 0, "_55": null, "_65": 0, "_72": null}
genCard contains all the CC data required by Stripe (number, exp_month, exp_year, cvc), and formBody formats the CC data in accordance to all the documentation and guides I've found online. However, the API response I'm receiving is not the expected payment token, but instead {"_40": 0, "_55": null, "_65": 0, "_72": null}.
I believe I've followed Stripe's documentation, but either the header data is incorrect or the body data is mis-formatted.
Is anybody familiar with this process? What am I missing?
For anybody interested, the following solution worked:
async function testStripe() {
const genCard = {
'card[number]': "4242424242424242",
'card[exp_month]': "11",
'card[exp_year]': "25,
'card[cvc]': "111"
}
const results = await fetch("https://api.stripe.com/v1/tokens", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer " + "sk_test_4eC39HqLyjWDarjtT1zdp7dc",
},
body: Object.keys(genCard)
.map(key => key + '=' + genCard[key])
.join('&'),
}).then(response => response.json())
console.log('\n\n\nlogging: \n', genCard, '\n', 'blank', '\n', results)
return
}
Wrap your fetch in an async function and await the results
The fetch body must be key->value pairs of the card data
Use your Stripe Publishable Key to authenticate api requests
Your api response should look something like this:
{"card": {"address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "cvc_check": "unchecked", "dynamic_last4": null, "exp_month": 11, "exp_year": 2022, "fingerprint": "Xt5EWLLDS7FJjR1c", "funding": "credit", "id": "card_1INjaU2eZvKYlo2C5O5qqIFW", "last4": "4242", "metadata": {}, "name": null, "object": "card", "tokenization_method": null}, "client_ip": "66.42.75.92", "created": 1614020214, "id": "tok_1INjaU2eZvKYlo2CDjL8bde4", "livemode": false, "object": "token", "type": "card", "used": false}

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));

Lambda - headObject fails (NotFound) though objectCreated is the event

In a lambda function with the event: s3:ObjectCreated:*, calling head object on the created object returns a NotFound error.
module.exports.handler = async function(event, context, callback) {
try {
const Bucket = event.Records[0].s3.bucket.name;
const Key = event.Records[0].s3.object.key;
console.log('Bucket', Bucket);
console.log('Key', Key);
const objectHead = await s3.headObject({ Bucket, Key }).promise();
console.log('Alas! I will never discover that the objectHead is:', objectHead);
callback();
} catch(err) {
console.error('Error', err);
callback(err);
}
}
And this is the error I get:
{
NotFound: null
message: null,
code: 'NotFound',
region: null,
time: 2018-02-19T11:06:35.894Z,
requestId: 'XXXXXXXXXXX',
extendedRequestId: 'XXX.....XXX',
cfId: undefined,
statusCode: 404,
retryable: false,
retryDelay: 77.24564264820208
}
I've noticed that it says region null in the error. I suspect this is irrelevant as I'm 99% sure I'm setting it correctly:
const s3 = new AWS.S3({
region: 'us-east-1'
});
Here's the serverless.yml function declaration in case anybody's curious:
obj_head:
handler: obj_head.handler
events:
- s3:
bucket: ${self:provider.environment.BUCKET_NAME}
event: s3:ObjectCreated:*
role: arn:aws:iam::XXXXXXXXX:role/RoleWithAllS3PermissionsEver
And here is a sample for a received event:
{
"Records": [
{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"awsRegion": "us-east-1",
"eventTime": "2018-02-19T11:03:46.761Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AWS:XXX"
},
"requestParameters": {
"sourceIPAddress": "X.X.X.X"
},
"responseElements": {
"x-amz-request-id": "X",
"x-amz-id-2": "X/X/X"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "14122133-28e8-4cd9-907c-af328334c56b",
"bucket": {
"name": "BUCKET_NAME",
"ownerIdentity": {
"principalId": "X"
},
"arn": "arn:aws:s3:::BUCKET_NAME"
},
"object": {
"key": "input.key",
"size": X,
"eTag": "X",
"sequencer": "X"
}
}
}
]
}
It's puzzling that the object head isn't found though the very event that triggered the function is the object's creation.
Am I doing something wrong?
Any thoughts on where to look?
The object keyname value is URL encoded, and this was causing the issue. This behaviour is documented here:
The s3 key provides information about the bucket and object involved
in the event. Note that the object keyname value is URL encoded. For
example "red flower.jpg" becomes "red+flower.jpg".
When dealing with filenames that contains Unicode characters please see this answer from Alastair McCormack:
You need to convert the URL encoded Unicode string to a bytes str
before un-urlparsing it and decoding as UTF-8.