Tastypie deserialize results in {"error": ""} - json

I'm using tastypie with django. I have one line of code:
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
I use this code from the command line to send a post request to my webserver:
curl -X post -d "{ 'username' : 'user', 'password' : 'password' }" http://127.0.0.1:8000/api/employee/login/ --header "Content-Type:application/json"
When I run this, it results in a json response of
{"error": ""}
Looking at my server logs I see:
[15/Feb/2014 20:39:49] "post /api/user/login/ HTTP/1.1" 400 13
A log message logged immediately before the deserialize line will be logged successfully, but a log message logged immediately after the deserialize line will not be logged, so I am pretty sure the deserialize is wrong. Does anyone know what could be wrong or if I should consider something else as the problem?

Your JSON is not valid. Please check it here. The 400 (bad request) status should give you clue about that. It should be: {"username": "user", "password": "password"}. Here you have some solutions how to escape " char in CURL command. Tastypie unfortunately raises exception without message here but we can easily fix that for future to save time for other people which will use your API.
from tastypie.exceptions import BadRequest
from tastypie.serializers import Serializer
class VerboseSerializer(Serializer):
"""
Gives message when loading JSON fails.
"""
# Tastypie>=0.9.6,<=0.11.0
def from_json(self, content):
"""
Override method of `Serializer.from_json`. Adds exception message when loading JSON fails.
"""
try:
return json.loads(content)
except ValueError as e:
raise BadRequest(u"Incorrect JSON format: Reason: \"{}\" (See www.json.org for more info.)".format(e.message))
class MyResource(BaseModelResource):
class Meta:
serializer = VerboseSerializer(formats=['json'])

Related

Trying to make a POST request, works with cURL, get a 403 when using Python requests

I'm trying to get some JSON data from this API - https://ped.uspto.gov/api/queries
This cURL request works fine and returns what is expected:
curl -X POST "https://ped.uspto.gov/api/queries" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"searchText\":\"*:*\", \"fq\":[ \"totalPtoDays:[1 TO 99999]\", \"appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]\" ], \"fl\":\"*\", \"mm\":\"100%\", \"df\":\"patentTitle\", \"facet\":\"true\", \"sort\":\"applId asc\", \"start\":\"0\"}"
I have this python script to do the same thing:
from requests.structures import CaseInsensitiveDict
import json
url = "https://ped.uspto.gov/api/queries"
headers = CaseInsensitiveDict()
headers["accept"] = "application/json"
headers["Content-Type"] = "application/json"
data = json.dumps({
"searchText":"*:*",
"fq":[
"totalPtoDays:[1 TO 99999]",
"appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]"
],
"fl":"*",
"mm":"100%",
"df":"patentTitle",
"facet":"true",
"sort":"applId asc",
"start":"0"
})
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
but it returns a 403 error code and the following response header:
"Date":"Mon, 24 Oct 2022 16:13:58 GMT",
"Content-Type":"text/html",
"Content-Length":"919",
"Connection":"keep-alive",
"X-Cache":"Error from cloudfront",
"Via":"1.1 d387fec28536c5aa92926c56363afe9a.cloudfront.net (CloudFront)",
"X-Amz-Cf-Pop":"LHR50-P8",
"X-Amz-Cf-Id":"RMd69prehvXNAl97mo0qyFtuBIiY8r9liIxcQEmbdoBV1zwXLhirXA=="
I'm at quite a loss at what to do, because I really don't understand what my Python is missing to replicate the cURL request.
Thanks very much.
I was interested in this. I got an account with uspto.gov and acquired an access key. Their other API's work well. But the PEDS API? I kept getting the Cloudflare Gateway Timeout 503 error. While I was on their website, I looked into the PEDS API, I could not load any link to a https://ped.uspto.gov page.
I called them and they gave me an email address. I got this reply:
The PEDS API was taken down, because repeated data mining was bringing the entire PEDS System down.
The PEDS Team is working on a solution to fix the PEDS API, so that it can be re-enabled.
I tried it using PHP.
Cloudflare has been causing a lot of problems for curl.
I got a timeout.
I may have gotten past the 403 Forbidden, but did not have credentials and so the server dropped the connection.
An HTTP 504 status code (Gateway Timeout) indicates that when
CloudFront forwarded a request to the origin (because the requested
object wasn't in the edge cache), one of the following happened: The
origin returned an HTTP 504 status code to CloudFront. The origin
didn't respond before the request expired.
AWS Cloudflare Curl Issues
bypassing CloudFlare 403
How to Fix Error 403 Forbidden on Cloudflare
403 Forbidden cloudflare
██████████████████████████████████████████████████████████████
This is a conversion from you curl.
The Content-Type:application/data is added by default when you send JSON data.
I do not know about your json_data.dump or you putting the JSON in parentheses.
import requests
headers = {
'accept': 'application/json',
}
json_data = {
'searchText': '*:*',
'fq': [
'totalPtoDays:[1 TO 99999]',
'appFilingDate:[2005-01-01T00:00:00Z TO 2005-12-31T23:59:59Z]',
],
'fl': '*',
'mm': '100%',
'df': 'patentTitle',
'facet': 'true',
'sort': 'applId asc',
'start': '0',
}
response = requests.post('https://ped.uspto.gov/api/queries', headers=headers, json=json_data)

rails 5 api returns 301 from PORO

I have a Rails 5.0.0.1 API application that needs to return a simple PORO as json. I am using gem 'responders', '~> 2.3.0'
The object constructs correctly and works properly in the Rails server. It has only 4 attributes that are needed by the front-end.
The serializer is:
class WebsiteConfigSerializer < ActiveModel::Serializer
attributes :force_first_user_to_be_admin, :allows_delete_of_last_admin,
:is_private_website, :invite_only
end
The controller show method (the only method in the controller) is:
def show
config = WebsiteConfig.new
puts "Config: #{config.to_json}"
respond_to do |format|
format.json {render( json: config, status: 200 ) }
end
end
The log shows the request output, including the debugging puts statement:
Started GET "/config.json" for 127.0.0.1 at 2016-09-03 18:23:32 -0400
Processing by WebsiteConfigController#show as JSON
Config: {"force_first_user_to_be_admin":true, "allows_delete_of_last_admin":false, "is_private_website":true, "invite_only":true}
[active_model_serializers] Rendered WebsiteConfigSerializer with ActiveModelSerializers::Adapter::Attributes (0.13ms)
Completed 200 OK in 2ms (Views: 1.2ms | ActiveRecord: 0.0ms)
as expected.
The output of cURL is:
curl -sb -H "Accept:application/json" -H "Content-Type:application/json" http://localhost:3000/config
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx</center>
</body>
</html>
This is NOT what I expected.
wget output is EMPTY (0 bytes). Also not what I expected.
Obviously I am missing something. Any help will be appreciated.
Your request has been redirected, check if you have some authentication code like requiring login or something else, then added them to the curl command

REST API Testing: HTTP Post returns 500 with Frisby.js

I am using Frisby.js to submit a POST request with JSON data and test the JSON response. However, my query returns HTTP Status 500. The same POST request works fine in CURL in my command line, as well as Postman. What could be the problem?
CURL request: curl -H "Content-Type: application/json; charset=UTF-8" -X POST -d "json_data" url
FRISBY test:
frisby
.create("Submit request")
.post(url, json_data, {"json": true, "content-type": "application/json;charset=UTF-8"})
.expectStatus(200)
.inspectBody()
.toss();
OUTPUT with Frisby:
Destination URL may be down or URL is invalid, Error: ETIMEDOUT
F
Failures:
1) Frisby Test: Submit request
[ POST url]
Message:
Expected 500 to equal 200.
Stacktrace:
Error: Expected 500 to equal 200.
at null.<anonymous>
at null.<anonymous>
at Timer.listOnTimeout (timers.js:92:15)
Finished in 5.032 seconds
1 test, 1 assertion, 1 failure, 0 skipped
The 500 error and accompanying message that results "Destination URL..." is from Frisby itself, not your server. Frisby adds the error if the connection times out. Try increasing it to 10 seconds.
...
.get(url)
.timeout(10000)
...

How to post a json for a particular parameter using CURL

I try to do a POST request which contains number of parameters. One parameetr require a JSON file. I tried several options but i face issue with json. The parameter which requires json is 'swagger'..
Here is the curl request I try.[1] But looks like this is not accepted by server. Im getting following error;
"null is not supported"}curl: (6) Could not resolve host: swaggerimpl.json
How can i post the JSON using curl for a particular parameter?
[1]
curl -X POST -b cookies $SERVER/publisher/site/blocks/item-design/ajax/add.jag -d "action=implement&name=YoutubeFeeds&visibility=public&version=1.0.0&provider=admin&endpoint_type=http&implementation_methods=http&wsdl=&wadl=&endpointType=nonsecured&production_endpoints=http://gdata.youtube.com/feeds/api/standardfeeds&implementation_methods=endpoint" -H 'Content-Type: application/json' -d 'swagger=' #swaggerimpl.json
Edit :
Curl Command
curl -X POST -b cookies $SERVER/publisher/site/blocks/item-design/ajax/add.jag -d "action=implement&name=YoutubeFeeds&visibility=public&version=1.0.0&provider=admin&endpoint_type=http&implementation_methods=http&wsdl=&wadl=&endpointType=nonsecured&production_endpoints=http://gdata.youtube.com/feeds/api/standardfeeds&implementation_methods=endpoint" -d #swagger_impl.json -d #endpointconfig_impl.json;
Error;
at java.lang.Thread.run(Thread.java:695)
Caused by: java.lang.ClassCastException: org.mozilla.javascript.NativeJavaArray cannot be cast to java.lang.String
at
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
The suspect json file
swagger={
"apiVersion": "1.0.0",
"swaggerVersion": "1.2",
"authorizations": {
"oauth2": {
"scopes": [],
"type": "oauth2"
}
},
.........
}
The cast code:
public static boolean jsFunction_updateAPIImplementation(Context cx, Scriptable thisObj,
Object[] args, Function funObj) throws Exception, ScriptException {
boolean success = false;
if (args==null||args.length == 0) {
handleException("Invalid number of input parameters.");
}
NativeObject apiData = (NativeObject) args[0]; //This cause issue
Parameter that you are adding at the end should not contain the space. But if you remove this space then '#swagger.json' will be added as a test (not the file content). If you want to pass JSON as a parameter then you can add to the file parameter name like:
swagger={..}
It looks like workaround but curl will merge every -d parameter into the request parameters and it doesn't allow unquoted spaces.

Grails - JSON param request not passing to controller

I would like to pass a JSON to my requete.
But not possible to find the JSON.
#Secured(['ROLE_STUDENT'])
def validate() {
println params
println request.JSON
}
Result :
[controller:student, action:validate, id:2345444]
[:]
URL :
curl -i -H "Content-Type: application/json" -X POST -d '{"studentScores":[{"id":"2","score":"17"}],"comment":"good"}' 'http://localhost:8080/myapp/studient/2345444/validate' -H 'Cookie: JSESSIONID=3CCDC701553A2208428BB7135DDA5546'
I tried with GET and POST, and with à JQuery
$.ajax({
url: urlSubmit,
type: 'POST',
data: JSON.stringify(student),
contentType:"application/json; charset=utf-8",
dataType: "json"
});
Grails 2.4.4
Java 8 (compliance level java 7)
Tomcat 8
Some plugins :
spring-security-core:2.0-RC4
spring-security-facebook:0.16.2
spring-security-oauth2-provider:2.0-RC2
Need your help
See this: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html (9.3 GET).
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI
Request-URI being the important part here. There is no concept of body data in a GET requests.
So, change to POST and your request should work.
For first u have an error in your url in curl :)
http://localhost:8080/myapp/STUDIENT/2345444/validate
try this code
def json = JSON.stringify(params)
but I don't sure.