HTTP request to Cloud-Convert not working - fetch-api

I am trying to use fetch to POST an API call to Cloud Convert and getting the following error:
message: "The given data was invalid."
code: "INVALID_DATA"
errors: {...}
tasks: Array(1)
0: "The tasks field is required."
Here is my code (on Wix):
export async function convertMp4toMp3(fileUrl, filename) {
filename = filename.replace(/mp4/gi, "mp3")
let job = {
tasks: {
"import-2": {
"operation": "import/url",
"url": fileUrl
},
"task-1": {
"operation": "convert",
"input_format": "mp4",
"output_format": "mp3",
"engine": "ffmpeg",
"input": [
"import-2"
],
"audio_codec": "mp3",
"audio_qscale": 0
},
"export-1": {
"operation": "export/google-cloud-storage",
"input": [
"task-1"
],
"project_id": "project-id",
"bucket": "bucket",
"client_email": "client_emailXXXXXXX",
"file": filename,
"private_key": "My Private Key
}
}
}
let options = {
"method": "POST",
"body": job,
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}
let response = await fetch("https://api.cloudconvert.com/v2/jobs", options)
console.log(response.json())
}
As you can see, the "tasks" field is populated with the jobs...

The fetch API does not automatically encode JSON.
Try:
let options = {
"method": "POST",
"body": JSON.stringify(job),
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}

Related

Appsync vtl template does not work with #set variable, but does with a hardcoded string?

So the two templates below are identical except the first one uses a hard-coded json string for the "input" variable, and the latter uses a #set map variable wrapped with $util.toJson.
Should't they both have an equal result input variable for use in the lambda step finction?
So this template works as expected:
{
"version": "2018-05-29",
"method": "POST",
"resourcePath": "/",
"params": {
"headers": {
"content-type": "application/x-amz-json-1.0",
"x-amz-target":"AWSStepFunctions.StartSyncExecution"
},
"body": {
"stateMachineArn": "arn:aws:states:us-east-2:712123061483:stateMachine:add-cognito-pool-user",
"input": "{ \"tenantId\": \"$context.identity.claims.name\" }"
}
}
}
This one does not:
#set( $myMap = {
"tenantId": $context.identity.claims.name
} )
{
"version": "2018-05-29",
"method": "POST",
"resourcePath": "/",
"params": {
"headers": {
"content-type": "application/x-amz-json-1.0",
"x-amz-target":"AWSStepFunctions.StartSyncExecution"
},
"body": {
"stateMachineArn": "arn:aws:states:us-east-2:712123061483:stateMachine:add-cognito-pool-user",
"input": $util.toJson($myMap)
}
}
}
Why doesn't the latter work? It just behaves as if there is no "tenantId" variable set in my lambda step function.

Implement different response with WireMock when no request(s) match

I'm trying to stub a RESTful API. One of the resources return the details when the resource is (indeed) found, or an HTTP 404 (Not Found) when, eventually, there is no resource for the given URL.
This is my simplified stub/mapping:
{
"mappings": [
{
"name": "Retrieve Items",
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
},
"response": {
"bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
"headers": {
"content-type": "application/json"
},
"status": 200
}
}
]
}
Then I have several JSON files (in /home/wiremock/__files/items-api/responses/retrieve/ to match the requests against — but I can't find a way to implement the HTTP 404 (Not Found) scenario:
{
"timestamp": {{ now }},
"status": 404,
"error": "Not Found",
"message": null,
"path": "{{ request.path }}"
}
With this config I get back (the expected, but not useful for my use case) response from WireMock that the file name uuid-sent-in-request.json is not found.
Is there a way to implement this behavior currently?
Tom's answer will work as well. I think the benefits to his solution are that they aren't tied to specific request URLs, but my suggestion is to have a specific mapping for the files that will match with their specific JSON files, and a catch-all mapping for un-matched files. By assigning the requests with JSON responses a higher priority, WireMock will check those first, and if the request does not match any of the values specified in that mapping, will then go on to check if the second mapping matches, and return a 404.
{
"mappings": [
{
"name": "Retrieve Items - Success",
"priority": 1, // arbitrary number lower than the second priority
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/(UUID1|UUID2|UUID3|UUID4)"
},
"response": {
"bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
"headers": {
"content-type": "application/json"
},
"status": 200
}
},
{
"name": "Retrieve Items - 404 Not Found",
"priority": 5, // arbitrary number that is higher than 1
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
},
"response": {
"status": 404
}
}
]
}
Currently you would need to write a ResponseDefinitionTransformer to get the behaviour you're looking for.
It would need to check whether the ResponseDefinition passed in the parameter required a file, then if so check whether the file exists by doing something like:
try {
fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
return WireMock.notFound().withBody("custom body");
}
// Otherwise return the unmodified response definition

WireMock set optional Parameters possibly?

i am very new here. I look up to setup die optional parameters in my Pattern. I have already read the documentary WireMock, but I have not found anything suitable.
My question is, can I query the parameters in any order =?
The next one would is ,y caseInsensitive doesn't work. I dont know why.
{
"priority": 1,
"request": {
"method": "GET",
"headers": {
"Content-Type": {
"equalTo": "application/json",
"caseInsensitive": true
}
},
"urlPattern": "/example\\?name=([a-zA-Z0-9]*)&id=([a-zA-Z0-9]*)"
},
"response": {
"status": 200,
"bodyFileName": "example/test.json"
}
}
As you've written your urlPattern, the query parameter matching is not order indifferent. If you want the query parameters to indifferent, you'd need to do something like...
{
"priority": 1,
"request": {
"method": "GET",
"headers": {
"Content-Type": {
"equalTo": "application/json"
}
},
"urlPath": "/example",
"queryParameters": {
"name": {
"matches": "([a-zA-Z0-9]*)"
},
"id": {
"matches": "([a-zA-Z0-9]*)"
}
}
},
"response": {
"status": 200,
"bodyFileName": "example/test.json"
}
}
The result of the query comes back the same answer.
i want, if i call my request, that the order of Parameters doesn't matter.
example Request: /example?name=max&id=01
example2 Request: /example?id=01&name=max
it should be get same Response.
And it should be case-insensitive.

Wiremock standalone dynamic response array of objects is not working with bodyPatterns and matchesJsonPath

I am using wiremock to stubbing the requests. I have created a json file to get a response:
{
"request": {
"method": "POST",
"urlPath": "/nested/transform",
"bodyPatterns": [
{
"matchesJsonPath": "$.name.[0].first"
},
{
"matchesJsonPath": "$.name.[1].first"
}
]
},
"response": {
"status": 200,
"body": "{\"firstName\": \"$(name.[0].first)\", \"lastName\": \"$(name.[1].first)\"}",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["body-transformer"]
}
}
My request and response are as below:
Request
{
"name": [
{
"first": "Vijay"
},
{
"first": "Sagar"
}
]
}
Here I receive very beard response and it is not parsed as I want.
Response which is not my expected result:
{
"firstName": "[{first=Vijay}, {first=Sagar}]",
"lastName": "[{first=Vijay}, {first=Sagar}]"
}
Expected result is: I'm willing to receive the following response based on above request and stubbed json:
{"firstName": "Vijay","lastName": "Sagar"}
How can I get the expected result as I tried a lot but was unable to match response parameters?
When working with a JSON response, I prefer to use the bodyFileName as this that escaping isn't necessary.
__files/nested_json_template.json
{
"firstName": "{{jsonPath request.body '$.name.[0].first'}}",
"lastName": "{{jsonPath request.body '$.name.[1].first'}}"
}
mappings/nested_json_mapping.json
{
"request": {
"method": "POST",
"urlPath": "/nested/transform",
"bodyPatterns": [
{
"matchesJsonPath": "$.name.[0].first"
},
{
"matchesJsonPath": "$.name.[1].first"
}
]
},
"response": {
"status": 200,
"bodyFileName": "nested_json.json",
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"]
}
}

Mapping by request's body use two matches

I has http request with body:
endpoint = http://127.0.0.1:54400/json
reqBody:
{
"action": "Handler:GET_DICTIONARY",
"locale": "ro",
"data": {"dictionary_type":"MTS"}
}
I need to get stubbed response.
Here my Wiremock mapping:
{
"request": {
"method": "POST",
"bodyPatterns": [
{
"contains": "Handler:GET_DICTIONARY"
}
]
},
"response": {
"headers": {
"Content-Type": "application/json"
},
"status": 200,
"fixedDelayMilliseconds": 3000,
"bodyFileName": "t2a/micb/webclient/_mts_response.json"
}
}
But I has many another requests that content request's body with text:
"Handler:GET_DICTIONARY"
So as result I need to mapping also by
"dictionary_type":"MTS"
because text
and
"dictionary_type":"MTS" AND "Handler:GET_DICTIONARY" create UNIQUE request.
So how I can mapping by request's body use this two matches?
I would suggest to add "matchesJsonPath" in addition to your "contains"
"bodyPatterns": [
{
"matchesJsonPath": "$.data[?(#.dictionary_type == 'MTS')]"
}
]
That will guarantee that all the request with dictionary_type = MTS will mapped to that response.