How to send a boolean to python-eve? - rest

I'm trying to update a boolean value using python eve, but I always receive the same error,
_issues: {deleted:must be of boolean type}
deleted: "must be of boolean type"
_status: "ERR"
I've tried sending the field as true (setting javascript type) 'True' and 'true' (as text) and 1, but the error is always the same.
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=True
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=true
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=1
Any idea?
Regards
Gaston
settings.py
entity= {
'resource_methods': ['GET', 'POST'],
'schema': schema,
'datasource': {
'filter': {'$or':[{'deleted':{'$exists':0}},{'deleted':False}]}
}
}
schema = {
'name': {
'type': 'string',
'minlength': 1,
'maxlength': 50,
'required': True,
},
'code': {
'type': 'string',
},
'deleted':{
'type':'boolean',
'default':False
}
}
Full Request
Request URL:http://localhost:5000/campaign/532f797da54d75faabdb25d5
Request Method:PUT
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,no;q=0.6,es;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:112
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:5000
If-Match:3c7bc93e3c7d60da62f350ac990c16e29b08660f
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/static/index.html
X-Requested-With:XMLHttpRequest
Form Dataview parsed
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=True
Response Headersview source
Access-Control-Allow-Headers:
Access-Control-Allow-Max-Age:21600
Access-Control-Allow-Methods:HEAD, GET, PUT, POST, DELETE, OPTIONS, PATCH
Access-Control-Allow-Origin:*
Content-Length:69
Content-Type:application/json
Date:Mon, 24 Mar 2014 00:30:10 GMT
Server:Werkzeug/0.9.4 Python/2.7.5
Set-Cookie:session=eyJfcGVybWFuZW50Ijp0cn

If you change your schema to coerce deleted value to bool, you can send int or str values and have it converted to bool on insert/update
First, create a function to convert whatever comes, to bool:
to_bool = lambda v: v if type(v) is bool else str(v).lower() in ['true', '1']
Then, change the deleted in the schema to use the function to coerce values, like this:
'deleted':{
'type':'boolean',
'coerce': to_bool,
'default':False
}
With this, you can per example send deleted with values such as '0', 0, 'false' or 'False' yelding to boolean false, or '1', 1, 'true' or 'True' resulting in true

This happens only when you send the request in the content type of form-data or application/x-www-form-urlencoded. In case of AJAX requests, sending boolean value works.
var payload = {
"deleted": false
};
var xhr = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(payload),
dataType: "json",
url: "some url"
})

Your payload should be a dict like:
payload = {"somebool": False}
then you convert it to a json string:
payload_json = json.dumps(payload)
which results in a lowercased bool value in a string:
'{"f5only": false}'
then you shoulc be able to post or patch it:
requests.post("{0}/endpoint/".format(api_server), headers=headers, data=payload_json)

Related

How i can perform a POST request using fireFox RESTClient add-in

I have this function to perform a POST request to a SharePoint Online site collection:-
function SetListColumnReadOnly() {
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: "https://****.sharepoint.com/_api/web/lists/getByTitle('tickets')/fields/getbytitle('defineFields')",
method: "POST",
data: JSON.stringify({
'__metadata': {
// Type that you are modifying.
'type': 'SP.FieldText'
},
'ReadOnlyField': true
}),
headers:
{
// IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
// "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
"IF-MATCH": "*",
"X-HTTP-Method": "PATCH",
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
//"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, error) {
console.log("Failed");
}
});}
Now how we can run this POST inside the FireFox's RESTClient addin or anyother tool using the browser credentials?
when i tried this >> i got forbidden error:-
Also with those headers:-

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

Creating new document with Firestore REST API and Local Emulator Suite for Integration Test, Returning Error 400: Problem with Request Body?

I recently posted a question regarding creating a document in a collection in the local emulator suite using a HTTP Post Request with Axios.
Creating new document with Firestore REST API and Local Emulator Suite, Returning Error 404: Problem with Path Parameter
My previous error was a 404 error with the URL path parameter. Since making changes to that, now I’m receiving a 400 error. The following is the code:
First, using a post request to create an authenticated user ID token and storing that in a variable. No issues here.
//HTTP Post Request to create an auth ID, storing ID Token in variable
const createUserResponse = await axios.post(createUserInstance.url, createUserInstance.data, createUserInstance.config);
const userIdToken = createUserResponse.data.idToken;
const userLocalId = createUserResponse.data.localId;
console.log(userIdToken);
console.log(userLocalId);
Second, writing the request body. I’ve modified the URL which works now. I’ve also re-modified the data body to make sure it’s in the correct format.
Wondering if the issue is in:
the way I’ve written the query parameters (do I need to specific the new document name? is the API key the problem?)
the formatting of the data request body : according to the documentation a new document is automatically generated. I’d presume fields would be read as containing the key-value pairs to include in the document fields.
the formatting of the headers. I’ve checked and re-checked this. My userIDToken contains a string
//create a document in the user collection
//request body
const createDocumentInstance : createPostRequest = {
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=<API_KEY>',
data: {
'fields': {
'localId': 'hello',
}
},
//directly pasted IdToken as using the variable resulted in problem with ' ' error
config: {
'headers':
{
'Content-Type': 'application/json',
'Authorization': `Bearer ${userIdToken}`,
}
}};
To make sure of what I was looking at, I logged the entire request in my console. This is what it looks like.
console.log
{
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: { fields: { localId: 'hello' } },
config: {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU0NTQ2MDgsInVzZXJfaWQiOiI1Vmt3TUtRc1k0THJRTkRWaXpFYmdnYnExOVNyIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTQ1NDYwOCwiZXhwIjoxNjY1NDU4MjA4LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IjVWa3dNS1FzWTRMclFORFZpekViZ2dicTE5U3IifQ.'
}
}
}
Finally, making the post request on Axios. Exact same syntax as my previous post request.
//Post Request to create a document
const createDocument = await axios.post(createDocumentInstance.url, createDocumentInstance.data, createDocumentInstance.config);
const docReference = createDocument.data;
console.log(docReference);
When running this, the following error is returned:
{
message: 'Request failed with status code 400',
name: 'Error',
description: undefined,
number: undefined,
fileName: undefined,
lineNumber: undefined,
columnNumber: undefined,
stack: 'Error: Request failed with status code 400\n' +
' at createError (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/createError.js:16:15)\n' +
' at settle (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/core/settle.js:17:12)\n' +
' at IncomingMessage.handleStreamEnd (/Users/georgettekoo/Documents/Code/Okane/Okane-Firebase-Backend-Deprecated/functions/node_modules/axios/lib/adapters/http.js:293:11)\n' +
' at IncomingMessage.emit (node:events:539:35)\n' +
' at endReadableNT (node:internal/streams/readable:1344:12)\n' +
' at processTicksAndRejections (node:internal/process/task_queues:82:21)',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6Im15ZW1haWxAZW1haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJhdXRoX3RpbWUiOjE2NjU2MzAwMTUsInVzZXJfaWQiOiJEMTBoblpsek9nQWR0ZlJlNm1VUDBOY2ZtNm5pIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJteWVtYWlsQGVtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn0sImlhdCI6MTY2NTYzMDAxNSwiZXhwIjoxNjY1NjMzNjE1LCJhdWQiOiJva2FuZS1jcnVkLWRldiIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9va2FuZS1jcnVkLWRldiIsInN1YiI6IkQxMGhuWmx6T2dBZHRmUmU2bVVQME5jZm02bmkifQ.',
'User-Agent': 'axios/0.24.0',
'Content-Length': 30
},
method: 'post',
url: 'http://localhost:8080/v1beta1/projects/okane-crud-dev/databases/(default)/documents/test?key=AIzaSyCQSnirvajGL5Uok34OgEn7tF1S_tp5sa0',
data: '{"fields":{"localId":"hello"}}'
},
code: undefined,
status: 400
}
Not sure what I'm missing and where the issue is. Does anyone have any hints?

sending data to an axios http request from function parameter

let name = "myname"
function updateTodo(name) {
axios.put('https://jsonplaceholder.typicode.com/todos/1', {
title: name,
completed:true
})
.then(res=>showOutput(res))
.catch(err=>console.log(err))
}
I just wanted to send name variable as a function parameter to title data and it shows me that am sending empty data on how to fix this one.
If you want to send JSON in an HTTP request body, remember to set the header Content-Type to application/json.
E.g:
const body = {
title: name,
completed: true
};
axios.put('https://jsonplaceholder.typicode.com/todos/1', body, {
headers: {
'Content-Type': 'application/json'
}
});
Hope it helps.
Enjoy!

Sending data in 'Request Payload' using amplifyjs

I have a javascript object to be sent to server as follow :
var input = {a: 'aaa', b: 'bbb', c: 'ccc'};
And I want to send 'a' property in url like this
http://localhost/rest/customer/aaa
That's fine with url substitution feature in amplifyjs as follow :
amplify.request.define('update-customer', 'ajax', {
url : 'rest/customer/{a}',
dataType: 'json',
type : 'PUT'
contentType : 'application/json; charset=utf-8;
});
amplify.request('update-customer', { a : input.a, data : input });
The point I am struggling with is that I would like to send b and c property as a form data in json format as a 'Request Payload', however it is failed becauseof the form data is sent as follow :
Request Payload :
data : {b : 'bbb', c : 'ccc'}
So what I want to achieve is to remove 'data' key in 'Request Payload' as follow :
Request Payload :
{b : 'bbb', c : 'ccc'}
I tested this in REST Client program and was successed.
To wrap up my question, How to send data attached in Request Body without key name using amplifyjs?
Thanks in advance.
Try with:
amplify.request.define('update-customer', 'ajax', {
url: 'rest/customer/{a},
dataType: 'json',
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data: {
b : '{b}',
c : '{c}'
}
});
amplify.request('update-customer', { a : input.a, data : input });
This solution has a problem if input.b or input.c are null. Check this post for further details