fetchMock: uncaught typeError - reactjs

I have mocked my API-Respones with fetchMock (v.5.13.1). I have been working with it for a quite long time now and I didn't see this kind of behaviour yet.
I mocked two GET responses that are very similar.
fetchMock.get('glob:*/shippings/',"results":[
{"id": "1234", "status": "RELEASED", "foo": "bar"},
{"id": "5678", "status": "CREATED", "foo": "bar"},)
fetchMock.get('glob:*/shipping/myId1234',
{"id": "1234", "status": "RELEASED", "foo": "bar"})
Now, the first one works properly, but the second get returns me this error message:
fetch-mock.js:187 Uncaught TypeError: Invalid status RELEASED passed
on response object. To respond with a JSON object that has status as a
property assign the object to body e.g. {"body": {"status:
"registered"}}
I have an assumption, that I cant mock some response that contains a status, because thats in a way a reserved attribute for status codes, but I am not quite sure and I cant find any similar errors online.

For the second request to fetchMock, it assumes status to be one of the standard codes supplied as an integer. According to the docs, the config supplied to fetchMock expects the following params
If an object only contains properties from among those listed below it
is used to configure a Response to return
body: String | Object
Set the Response body. See the non-config Object section of the docs
below for behaviour when passed an Object
Server responded ok { token: 'abcdef' }
status: Integer
Set the Response status
200, 404, 503
headers: Object
Set the Response headers
{'Content-Type': 'text/html'}
redirectUrl: String
The url from which the Response should claim to originate from (to
imitate followed directs). Will also set redirected: true on the
response
throws: Error
Force fetch to return a Promise rejected with the value of throws
new TypeError('Failed to fetch')
However for a custom status attribute you can respond with a body
fetchMock.get('glob:*/shipping/myId1234', {
body: {"id": "1234", "status": "RELEASED", "foo": "bar"}
})

Related

React API call, render data with QuickBase's new RESTful API

I'm trying to figure out what i'm doing wrong here... I've been out of coding for awhile and trying to jump back in for an external application utilizing QuickBase's RESTful API. I'm simply trying to get data from QuickBase to be used outside in an external app to create charts/graphs.
I'm not able to use GET as it gives me only the field names and no data, if I use POST, then I get the values of these fields as well. I'm able to get all the data rendered in the console, but am struggling to get each field rendered to be used in the app.
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
}
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query',
{
method: 'POST',
headers: headers,
body: JSON.stringify(body)
})
.then(res => {
if (res.ok) {
return res.json().then(res => console.log(res));
}
return res.json().then(resBody => Promise.reject({status: res.status, ...resBody}));
})
.catch(err => console.log(err))
Hoping to get some help getting the data rendered to be used in React, as well as any tips from anyone who's used QuickBase's new API calls in their realm! And I apologize if it's an easy question/issue, haven't been in React for a couple years... and I'm feeling it!
Thanks!
A successful response from Quickbase for this call has a property data which is an array of the records returned. Each element of this array is an object where the FID for each field returned is a key for nested object - or objects for some field types - with the field's value. Here's a very contrived example:
{
"data": [
{
"1": {
"value": "2020-10-24T23:22:39Z"
},
"2": {
"value": "2020-10-24T23:22:39Z"
},
"3": {
"value": 2643415
}
}
],
"fields": [
{
"id": 1,
"label": "Date Created",
"type": "timestamp"
},
{
"id": 2,
"label": "Date Modified",
"type": "timestamp"
},
{
"id": 3,
"label": "Record ID#",
"type": "recordid"
}
]
}
If you put the data array of the response directly into state with const [quickbaseData, setQuickbaseData] = useState(res.data); for example, you need to keep the structure of the response in mind when accessing that data. If I want to get the value of FID 3 from the first record in the response I would need to use quickbaseData[0]["3"].value. For most field types value will be a string or integer but for some field types it will be an object. You can see the way values are returned for each field type in Field type details.
Depending on your needs you might consider processing the Quickbase response into a new, simpler array/object to use in your application. This is especially helpful if the value being returned needs additional processing such as converting into a Date() object. This would also allow you to make your application API agnostic since other than initially processing the response from Quickbase the rest of your application doesn't have to have any knowledge of how Quickbase returns queried data.
On the Quickbase side of things, there isn't the equivalent of 'SELECT *' so to get data for all fields of a table where you don't know the schema (or it changes frequently) you can run a GET on the Fields endpoint: https://developer.quickbase.com/operation/getFields an then use the field IDs in the response to make the POST call to /records/query

Postman response in different order to console log response from request

When using Postman to test an API a request, the response i get is unordered, which is what I want, i.e.:
}
"23": "Kevin",
"2": "James",
"12": "Michael"
}
However, when I log the response, it automatically sorts it to:
}
"2": "James",
"12": "Michael",
"23": "Kevin"
}
I am getting the response in a promise:
return this.client.post('/url', data)
.then(response => {
console.log('api response: ', response);
Is there anyway I can prevent the ordering of the response so I can render the data as desired? I am not sure where, or why the order of the data is different.
Any help will be massively appreciated!
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.

Firebase Cloud Firestore - Fail to write via REST API

This is not an authentication error, write is enabled on the database rules.
My cloud Firestore database looks like the picture below.
There is a COLLECTION called colA, inside it there is a DOCUMENT called docA, and inside it there are some fields (strings) stored.
On Postman, if I do GET https://firestore.googleapis.com/v1/projects/eletronica-ab6b1/databases/(default)/documents/colA/docA, I do receive the following answer, and it is correct:
{
"name": "projects/eletronica-ab6b1/databases/(default)/documents/colA/docA",
"fields": {
"fieldB": {
"stringValue": "ABCD"
},
"fieldA": {
"stringValue": "888"
}
},
"createTime": "2020-01-31T16:48:26.859181Z",
"updateTime": "2020-02-05T19:21:49.654340Z"
}
Now, when I try to write a new field (fieldC) via POST https://firestore.googleapis.com/v1/projects/eletronica-ab6b1/databases/(default)/documents/colA/docA, with JSON content:
{
"name": "projects/eletronica-ab6b1/databases/(default)/documents/colA/docA",
"fields": {
"fieldC": {
"stringValue": "1000"
}
}
}
After SEND, I receive this:
{
"error": {
"code": 400,
"message": "Document parent name \"projects/eletronica-ab6b1/databases/(default)/documents/colA\" lacks \"/\" at index 60.",
"status": "INVALID_ARGUMENT"
}
}
What I'm doing wrong? I really would like to write strings there via REST API.
Regards.
Updating a document is done with a PATCH request, according to the [reference documentation).
A POST request is used to create a new document in a collection, which probably explains the error you get: you're pointing to a document, but POST expects a collection path.

API Error response when creating a request transaction: Missing parameter: `type`

When creating the transaction using the Coinbase PHP Library I am getting the following error from the API; Missing parameter: type
I added debug statements to double check that the library is properly sending the type, which it is.
type: "request",
amount: "10",
description: "random string",
to: "test#email.com",
currency: "BTC"
Has anyone else encountered this issue recently? I'm thinking that it's currently an issue with the coinbase API.
Ran down the rabbit hole making sure that it is properly sending the type properly to the API
$transaction = Transaction::request([
'toEmail' => 'test#email.com',
'amount' => new Money(1, 'BTC'),
'description' => 'Test transaction'
]);
$client->createAccountTransaction($client->getPrimaryAccount(), $transaction);
Result:
{
"success": false,
"error": "Missing parameter: `type`"
}
Expected:
JSON data including information about the request
This is an API bug ... not a php/python... bug

How to fix the "Invalid JSON payload received. Unknown name" error

I try to get a proper response from the Google Safe Browsing API v4. Although I get the error "Invalid JSON payload received. Unknown name".
I have used a payload based on the payload example mentioned at https://developers.google.com/safe-browsing/v4/lookup-api
I have problems with the payload. I think it should be a string, not a real dict. When I use a dict I get the error: TypeError: has type , but expected one of: str, unicode
The code I used is:
result = urlfetch.fetch(url, method=urlfetch.POST, payload=payload)
The url is (with [api-key] is of course my api-key):
https://safebrowsing.googleapis.com/v4/threatMatches:find?key=[api-key]
The payload is the following string (not a python dict):
{
"client": {
"clientId": "myproject",
"clientVersion": "42" },
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["WINDOWS"],
"threatEntryTypes": ["URL"],
"threatEntries": [ {"url":"http://www.example.com/"} ] }
}
As output I expected some JSON which indicates that this url is safe. However I get the following result:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\n \"client\": {\n \"clientId\": \"myproject\",\n \"clientVersion\": \"42\"\n },\n \"threatInfo\": {\n \"threatTypes\": [\"MALWARE\", \"SOCIAL_ENGINEERING\"],\n \"platformTypes\": [\"WINDOWS\"],\n \"threatEntryTypes\": [\"URL\"],\n \"threatEntries\": [\n {\"url\":\"http://www.example.com/\"}\n ]\n }\n }\": Cannot bind query parameter. Field '{\n \"client\": {\n \"clientId\": \"myproject\",\n \"clientVersion\": \"42\"\n },\n \"threatInfo\": {\n \"threatTypes\": [\"MALWARE\", \"SOCIAL_ENGINEERING\"],\n \"platformTypes\": [\"WINDOWS\"],\n \"threatEntryTypes\": [\"URL\"],\n \"threatEntries\": [\n {\"url\":\"http://www' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": [similar as the message above]
}
]
}
]
}
}
Any ideas, what is wrong?
Thanks
The urlfetch should contain the HEADER Content-Type: application/json
result = urlfetch.fetch(url, method=urlfetch.POST, payload=payload, headers={'Content-Type': 'application/json'})

Resources