Server doesn't accept double quotes in the query - post

I'm trying to make the same request as here using requests and python. This is my code:
address = "0x800d0c1e4fb219a2d9bd2f292aa91abdcd862915"
data= """{"query":"{poolSnapshots(where:{pool:"%s"}, orderBy: date){id baseTokenLiquidity datatokenLiquidity spotPrice}}","variables":null,"operationName":null}"""%(address)
response = requests.post('https://v4.subgraph.polygon.oceanprotocol.com/subgraphs/name/oceanprotocol/ocean-subgraph', data=data).json()
But when I execute the code I got the following error:
GraphQL server error (client error): expected ,or} at line 1 column 39: 0
What am I missing? I'm texting the double quotes wrongly? Thanks for answers!

The API expects a stringified JSON that you wrapped into the triple quotes. The right way is to use json.dumps to stringify the query payload (dict). It will convert the payload data types to corresponding JSON types.
import requests
import json
address = "0x800d0c1e4fb219a2d9bd2f292aa91abdcd862915"
url = 'https://v4.subgraph.polygon.oceanprotocol.com/subgraphs/name/oceanprotocol/ocean-subgraph'
data = {
"query": "{poolSnapshots(where:{pool:\"%s\"}, orderBy: date){id baseTokenLiquidity datatokenLiquidity spotPrice}}" % address,
"operationName": None,
"variables": None,
}
response = requests.post(url, data=json.dumps(data))
print(response.json())

Related

FSharp.Data HTTP Utility RequestString response Body is prepended with the word "Text"

I'm making a simple web call (GET) to an api that returns some json. Trouble is, I can't parse it with Newtonsoft (or otherwise) because the HTTP Utility RequestString response.Body is prepended with the word "Text".
Text
"[{"name":"10 Years","desc":"","descData":null,"closed":false ...
What can I do to avoid this and get my json string as an actual json string?
If you take a look at the FSharp.Data Http Utils ResponseBody docs you will notice it returns a Discriminated Union with 2 options.
So you will want to handle it with something like this:
let myHttphandler resp =
match resp with
| Text txt -> txt |> customTextHandler
| Binary bytes -> bytes |> customBytesHandler
Of course, if you know you will always get text, use _ in your DU.
Your customTextHandler function will probably deserialize your json.

How to clear double quote marks in json?

I generated a json using NSJSONSerialization.This is my code:
// parameters is `Dictionary<String, AnyObject>?`
let json = try! NSJSONSerialization.dataWithJSONObject(parameters!, options: NSJSONWritingOptions.init(rawValue: 0))
request.HTTPBody = json
But my server received this:
"{login:23232432434,mobile_captcha:,password:22e233434}"=>"[FILTERED]"
It seems server takes the whole json as a key and I think this because of that ".Maybe there is other reasons,please help me!
Those aren’t brackets; they’re (double) quotes/quotation marks. In valid JSON, quotation marks inside strings must be escaped with \, e.g. "Hello \"World\"".
The Web service you’re using is returning invalid JSON.
http://jsonlint.com is a useful resource to validate JSON strings.

Post Method with NSDictionary Values using Swift

I'm completely new toSwift. I need to hit a Post Method webservice with NSDictionary parameters & get the JSON response. I tried usingAlamofire & also NSMutableUrlRequest. Nothing seems to workout for me. I either get 'JSON text did not start with array or object and option to allow fragments not set' error or 'Undefined Variable' response from the server. The same service works fine when I try using Objective-C. As I said earlier, I am completely new toSwift & need your assistance.
My base url: http://myofficeit.in/bizfeed/webservices/client.php
Parameter I wanna Pass:
Parameter =
{
UserName = xyz;
deviceModel = iPhone;
deviceToken = "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e";
emailid = "xyz#gmail.com";
location = Asia;
userMobileNo = 1234567890;
};
functionName = register;
The code I used for hitting the service is: http://pastebin.com/aaT4uhS7
Thanks
you can use like
let param: [String:AnyObject] = [
"UserName": iPhone,
"deviceToken": "949264bc cd9c6c851ee64cc74db9078770dd7d971618ec20ce91d2e6eb9f155e",
"emailid": "xyz#gmail.com",
"location": Asia,
"userMobileNo": 1234567890
]
Alamofire.request(.POST, "http://myofficeit.in/bizfeed/webservices/client.php/register", parameters: param).responseJSON { (req, res, json, error) in
print(req)
print(res)
print(json)
print(error)
}
for sample request in Alamofire
As broad as your question is, the broad will be my answer:
The first thing to do, is to get a clear idea about the web service API, which also requires a basic knowledge of the HTTP protocol. So, what you need to understand is, what the server expects in HTTP terminology.
You eventually will find out, how the server will expect its "parameters". Note, that there is no term like "parameters" in the HTTP protocol. So, you need to map them into something the HTTP protocol provides.
Most likely, in a POST request, "parameters" are transferred as the body of the HTTP message, as a content-type which is application/x-www-form-urlencoded, multipart/form-data or application/json.
According to the needs of the server, and with your basic knowledge of HTTP and NSURLSession, NSURLComponents etc., you compose the URL and the body of the request, set Content-Type header and possibly other headers and you are ready to go.
How this eventually looks like is given in the answer of #AnbyKarthik, which used Alamofire, and a command that composes a POST request whose parameters are send in the body whose content-type is x-www-form-urlencoded.

Cyrillic encoding in request

I already read the following: Send request to page with windows-1251 encoding from python
Yet I cannot print a correct string. I have tried nearly every combination of u''.join, encode and decode I could think about...
import requests
url = 'http://www.multitran.ru/c/m.exe'
payload = {'CL': '1', 's': 'foo', 'l1':'1'}
r = requests.post(url, data=payload)
# ????????? print(u''.join(r.text))
I'd be very glad to get a solution and an explanation, because I really do not get it!

Convert Rails Net::HTTP request to MD5 Hex Digest

In order to use a third-party API, I need to encode the Net::HTTP::Post request as an MD5 hex digest, which is then used as part of the signature. However, when I try to simply Digest::MD5.hexdigest(req), it throws a "Cannot convert to string error", and when I explicitly req.to_s, it just gives the MD5 of #<Net::HTTP::Post:0x112a0eef8>
I'm simply:
request = Net::HTTP::Post.new(url.path)
request.body = {
"key" => "val"
}.to_json
# later...
hexDigest = Digest::MD5.hexdigest(request)
which is the documented spec, I think: "[with the] JSON body containing the new information."
This is the relevant sample Java code they supply:
ByteArrayOutputStream requestOutputStream = new ByteArrayOutputStream();
httpMethod.getEntity().writeTo(requestOutputStream);
DigestUtils.md5Hex(requestOutputStream.toByteArray()).toLowerCase();
Any ideas?
Thanks!
Try to call 'to_s' method explicitly, it should help:
hexDigest = Digest::MD5.hexdigest(request.to_s)
The equivalent ruby code for those lines is:
OpenSSL::Digest::MD5.hexdigest(request.body)
httpMethod.getEntity() will return the json defined as the request body.
requestOutputStream.toByteArray() will return the array of bytes corresponding to the request body.

Resources