Flask API can receive posts from AJAX but not Postman - json

We have a Flask API that talks to multiple sources, a web app, and an external source. In the web app, we use AJAX to send a JSON post to the API which is successful. From an external source, whether it's postman or the VaRest Unreal Engine plugin, we get a 400 Error: Bad Request even though we use the correct content-type header.
If anyone can help us figure out why the posts we are sending aren't properly identified we would really appreciate it.
Thanks
This is the JS code from our web app, used to create the JSON which is sent through AJAX (this is the successful code)
var but1 = document.getElementById('but1');
const data1 = {
number: 1 ,
type: 1 ,
value: 100
}
but1.addEventListener("click", function() {
$.post(url, data1);
});
This is a post route in our python API that takes in the input and saves it to a file we have
#app.route('/button', methods=['POST'])
def button():
buttonLog = open("buttonLog.txt", "w")
buttonLog.write(request.form['number'])
buttonLog.close()
typeOf = int(request.form['type'])
value = int(request.form['value'])
return "success"
Here is our JSON post, with headers
Postman JSON
Postman Headers
The AJAX post works as intended, but the postman post/Unreal engine post are not being seen as "posts" to the API.

Related

Get Thumbnail from FORGE API but received status code 202

I'm trying to get thumbnail from Forge API here
https://forge.autodesk.com/en/docs/model-derivative/v2/reference/http/thumbnails/urn-thumbnail-GET/
`
I got it with Postman and axios successfully, and I tried it with RestSharp, HttpClient and GetThumbnail from DerivativesApi (Autodesk.Forge) in C# but only got status code 202 with message:
{"Result":"The thumbnail generating for this graph node is pending"}
I realized that RestSharp and HttpClient only receive code 202 and return results. I don't know how I can wait for code 200 and thumbnail.
Can anyone help me?
This is my code:
var request = new RestRequest($"https://developer.api.autodesk.com/modelderivative/v2/designdata/{nameHash}/thumbnail", Method.GET);
request.AddHeader("Authorization", $"Bearer {oauth.access_token}");
var client = new RestClient();
var restRes = client.Execute(request);
The 202 code typically indicates that the request has been accepted but the response is not available yet. Is it possible that you're asking for a thumbnail of a file that is still being processed by the Model Derivative service? Try inspecting the response headers, and see if there's one called x-ads-job-status which (according to the documentation) should tell you the status of the processing.

Postman: SyntaxError: Unexpected number in JSON at position 1 at JSON.parse

I am a beginner at web development and I am trying to use Postman to send a POST request to one of my application's APIs.
I am using the Next.JS framework to build my website.
Here is my API:
import type { NextApiRequest, NextApiResponse } from "next"
export default async (
req: NextApiRequest,
res: NextApiResponse,
) => {
const userData = JSON.parse(req.body)
res.status(200).json(userData)
}
I simplified my API until I caught the error, and I believe that it is related to the JSON.parse(req.body) line.
This is a print of the data that I used to test the API on Postman
I get the following error:
SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (\u003canonymous\u003e)
at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///(api)/./pages/api/login.ts:9:27)
Previously, I used this API to authenticate users, and everything worked fine, except when I tried to insert data into the body of a Postman POST request.
Can someone help me? I have no idea what to do.
If you want to deserialize the body from a POST request, you also have to send a request where the body contains any data because otherwise, req.body will be null and that is not valid json.

PUT requests with Custom Ember-Data REST Adapter

I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.

NodeJS HttpGet to a URL with JSON response

I'm trying to make a server-side API call using a RESTful protocol with a JSON response. I've read up on both the API documentation and this SO post.
The API that I'm trying to pull from tracks busses and returns data in a JSON output. I'm confused on how to make a HTTP GET request with all parameters and options in the actual URL. The API and it's response can even be accessed through a browser or using the 'curl' command. http://developer.cumtd.com/api/v2.2/json/GetStop?key=d99803c970a04223998cabd90a741633&stop_id=it
How do I write Node server-side code to make GET requests to a resource with options in the URL and interpret the JSON response?
request is now deprecated. It is recommended you use an alternative:
native HTTP/S, const https = require('https');
node-fetch
axios
got
superagent
Stats comparision
Some code examples
Original answer:
The request module makes this really easy. Install request into your package from npm, and then you can make a get request.
var request = require("request")
var url = "http://developer.cumtd.com/api/v2.2/json/GetStop?" +
"key=d99803c970a04223998cabd90a741633" +
"&stop_id=it"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
})
You can find documentation for request on npm: https://npmjs.org/package/request

How to JSON format an HTTP error response in webapp2

I am using webapp2 for development in App Engine. What I would like to do is to send a custom JSON formatted response in case of an error. For example when the request length is larger that a threshold, to respond with HTTP 400 and response body
{'error':'InvalidMessageLength'}
In webapp2, there is the option to assign error handlers for certain exceptions. For example:
app.error_handlers[400] = handle_error_400
Where handle_error_400 is the following:
def handle_error_400(request, response, exception):
response.write(exception)
response.set_status(400)
When webapp2.RequestHandler.abort(400) is executed, the above code is executed.
How is it possible to have different response formats (HTML and JSON) dynamically based on the above setup? That is, how it is possible to call different versions of handle_error_400 function?
Here is a fully working example that demonstrates how to have the same error handler for all kind of errors and if your URL starts with /json then the response will be an application/json (use your imagination on how you could make a good use of the request object to decide what kind of response you should provide):
import webapp2
import json
def handle_error(request, response, exception):
if request.path.startswith('/json'):
response.headers.add_header('Content-Type', 'application/json')
result = {
'status': 'error',
'status_code': exception.code,
'error_message': exception.explanation,
}
response.write(json.dumps(result))
else:
response.write(exception)
response.set_status(exception.code)
app = webapp2.WSGIApplication()
app.error_handlers[404] = handle_error
app.error_handlers[400] = handle_error
In the above example you can easily test the different behaviours by visting the following URLs that will return a 404 which is the easiest error to test:
http://localhost:8080/404
http://localhost:8080/json/404