Node.JS Restful API posting json parameters - json

I'm writing a Restful api with node js and I'm facing a weird problem: I'm testing the API using a Chrome extension called postman and sending the json object below:
{
"items": [
{
"appid": 730,
"classid": "2222",
"id": 99,
"instanceid": "instanceID",
"market_name": "Market name"
},
{
"appid": 730,
"classid": "2222",
"id": 99,
"instanceid": "instanceID",
"market_name": "Market name"
}
],
"message": "Mensagem de teste",
"user": 76561197960275584
}
My problem is with the "user" property. When getting it from the server it returns me 76561197960275580 but the value sent was 76561197960275584. When I send it using string it works but when sending as number - which is like the consumer of the api sends data - it gives me this problem.
Here is some of my API code. It is using express 4.
var express = require('express');
var bodyParser = require('body-parser');
var api = express();
api.use(bodyParser.urlencoded({ extended: false }));
api.use(bodyParser.json());
api.post('/import', function importEndPoint(req, res) {
console.log('req.body.user=' + req.body.user);
});
Does anyone would have a tip for me to solve it?
Thanks in advance for any help.

Related

Telegram bot with aws lambda and API gateway

I am developing a telegram bot with python (telebot) , aws lambda and api gateway.
I have a problem in the lambda function and I can't understand why I have this kind of problem.
My lambda is this:
import telebot
import datetime
TOKEN = 'xxx'
def lambda_handler(event, context):
bot = telebot.TeleBot(TOKEN)
# Extract the message key over payload's body
message = json.loads(event['body'])
print(message)
# Split between three variables bellow
chat_id = message['chat']['id'] # Chat ID will guide your chatbot reply
sender = message['from']['first_name'] # Sender's first name, registered by user's telegram app
text = message['text'] # The message content
if text.lower().strip() == "/time":
current_time = datetime.strftime(datetime.now(), "%H:%M:%S")
bot.send_message(chat_id, "Right now its {} UTC.".format(current_time))
else:
pass
The error I get, running the test is this:
Response
{
"errorMessage": "'body'",
"errorType": "KeyError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n message = json.loads(event['body'])\n"
]
}
The given json file:
{
"update_id": 0000000,
"message": {
"message_id": 000000,
"from": {
"id": 00000000,
"is_bot": false,
"first_name": "myname",
"last_name": "mysurname",
"username": "sursurname",
"language_code": "it"
},
"chat": {
"id": 000000,
"first_name": "myname",
"last_name": "mysurname",
"username": "sursurname",
"type": "private"
},
"date": 1654697178,
"forward_from": {
"id": 00000000,
"is_bot": false,
"first_name": "mysurname",
"last_name": "mysurname",
"username": "sursurname",
"language_code": "it"
},
"forward_date": 0000000000,
"text": "ciao"
}
}
I cannot understand why it is not able to read the body in any way, maybe I am in the wrong library? Do you have any suggestions to help me with this?
event['body'] is almost definitely not the correct key to access data passed through an event. The event passes information in a nested dictionary and you'll need to figure out how to drill down to the correct key.
I solved it by doing this:
json_str = json.dumps(event)
resp = json.loads(json_str)
chat_id = resp['message']['chat']['id']
message_text = resp['message']['text']
message_chat_id = resp['message']['chat']['id']
message_username = resp['message']['from']['first_name']
bot = telebot.TeleBot(TOKEN)
bot.send_message(chat_id, "Hey, I understood this message!, hi {}".format(message_username))

400 Parser error with Google API POST call

I am trying to make POST call towards Search Console API. I got my example running under API Explorer, however when I try to make the same call from my meteor project, I am getting error:
Object {error: Object} error: Object code: 400 errors: Array[1]
message: "Parse Error"
My code:
function fetchSEOForWebsite(website) {
var call = 'webmasters/v3/sites/' + 'mdbootstrap.com' + '/searchAnalytics/query'
var params = {
"searchType": "web",
"dimensions": [
"query",
"date",
"page"
],
"startDate": "2016-02-06",
"endDate": "2016-02-08"
}
GoogleApi.post(call, {
params: params
}, function(error, answer) {
console.log(answer);
});
}
From Chrome console I can see POST payload:
searchType=web&dimensions=query%2Cdate%2Cpage&startDate=2016-02-06&endDate=2016-02-08
The same query works perfectly fine from API Explorer :
POST https://www.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fmdbootstrap.com/searchAnalytics/query?key={YOUR_API_KEY}
{
"searchType": "web",
"dimensions": [
"query",
"date",
"page"
],
"startDate": "2016-02-06",
"endDate": "2016-02-08"
}
What am I doing wrong?
I am using Meteor Google Api
https://github.com/percolatestudio/meteor-google-api
UPDATE:
I also checked paylod sent via API Explorer and it's different:
{ "searchType": "web", "dimensions": ["query","date","page"
], "startDate": "2016-02-06", "endDate": "2016-02-08" }
So it looks like for some reason my params are not passed as a JSON object to call...
From percolate:google-api package Readme
GoogleApi is a Google OAuth authentication wrapper around HTTP, so it
takes the same arguments. For example, to pass a JSON body in
GoogleApi.post, use:
GoogleApi.post('/your/api/path', { data: jsonBody });
So I would try with data: instead of params:

Posting data in a JSON file in AngularJS - (using django REST here to create that JSON file.)

I am using AngularJS along with Python & Django and Django REST API.
There is a JSON file created by the REST API and I need to post data into it using Angular $http.post().
I need to know if it is possible or not.
Im majorly getting 403(Forbidden) and 400(BAD REQUEST) errors on post..
$http({
method: 'POST',
url: '<JSON FILE URL>',
data: $scope.tmpDataSet,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}});
This is my .post() method. where im fetching the data from a form made in angular and storing it in 'tmpDataSet'. Its being created properly and im able to store into the array.
Im just not able to write it into the JSON file.
The structure of my JSON file is
{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"name": "fff",
"mobile_no": "fff",
"email": "n#gmail.com",
"message": "dfdf",
"id": 1
},
{
"name": "asd",
"mobile_no": "0987654321",
"email": "asd#gmail.com",
"message": "no",
"id": 2
}
]
If any more code detail is needed please comment.
This issue was solved by adding CSRF tokens to the angular app and using the regular $http.post() function with all the parameters.
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
and,
$http.post('<URL>', item).error(function(data,status,headers,config){
console.log('COULDNT POST!');
}).success(function(data, status, headers, config){
console.log('POSTED!');
});

FIWARE: token_script error parsing json response

I am trying to generate an access code using the script
https://raw.githubusercontent.com/fgalan/oauth2-example-orion-client/master/token_script.sh
I believe the response json has changed and the sed pattern is not working anymore.
How can I generate a valid access token?
Json response:
{
"access": {
"token": {
"issued_at": "2015-05-12T14:29:03.523315",
"expires": "2015-05-12T15:29:03Z",
"id": "?????",
"audit_ids": [
"????"
]
},
"serviceCatalog": [],
"user": {
"username": "pedro#viur.pt",
"roles_links": [],
"id": "pedro-almeida",
"roles": [],
"name": "pedro#viur.pt"
},
"metadata": {
"is_admin": 0,
"roles": []
}
}
}
line that generates the token
TOKEN=`echo $RESP | sed "s/{\"access\":{\"token\":{.*\"id\":\"\(.*\)\"},\"user.*$/\1/g"`
I have tried to use the access:token:id returned but it does not work.
The new id is also shorter then the old ones
Thanks
This problem was caused by the IdM migration at FIWARE Lab in early May 2015. After be aware of it, the PEP at orion.lag.fiware.org and token generation script have been fixed.
Please, donwload again the token_script.sh file and try again. It should work.

Include root in django rest framework responses

I have a ready Django project that serves JSON via the rest_framework and its viewsets. Now I would like to write the client using Ember. Here is my setup:
Django 1.6.5
Ember 1.6.1
Ember-Data 1.0.0-beta.8.2a68c63a
jQuery 2.1.1
My Django server runs on the default port 8000 under localhost. I test my Ember application by opening index.html in the browser. Therefore, I customised the ApplicationAdapter like so
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:8000',
});
I try to fetch a list of artists from http://localhost:8000/artists. The specified route is
App.ArtistsRoute = Ember.Route.extend({
model: function() {
this.store.find('artists');
}
});
And the response I get back from the server when I open the mentioned url in the browser is
[
{
"id": 1,
"name": "Kollegah",
"origin": "Germany",
"genre": "German Rap"
},
{
"id": 2,
"name": "Peter Fox",
"origin": "Germany",
"genre": "Hip-Hop"
},
{
"id": 3,
"name": "Farid Bang",
"origin": "Germany",
"genre": "German Rap"
},
{
"id": 4,
"name": "Eko Fresh",
"origin": "Germany",
"genre": "German Rap"
}
]
When fetching the data I these two Ember errors:
-Error while processing route: artists No model was found for 'artists' Error: No model was found for 'artists'
-No model was found for 'artists' Error: No model was found for 'artists'
The problem is that I have specified a model already
var attr = DS.attr;
App.Artist = DS.Model.extend({
name: attr,
origin: attr,
genre: attr,
});
I suppose the problem is the missing root element at the beginning of each JSON response. I suggest it should look like this example from the Ember Guides:
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": ["1", "2"],
"user" : "dhh"
},
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
After searching a short while I found a similar problems with Rails. I tried out the solution for Django mentioned in another Stackoverflow question but I got the same errors.
Does anybody know a server-side solution for this problem? The Ember Data Django Adapter could be one for the client side. Unfortunately, it is designed as a node plugin and at the moment I don't use it for my project.
The Ember Data Django Adapter is the most simple way of solving your problem, and if you pay attention to the docs, there are instructions for using it without ember-cli.