How to get a price from json data, binance api p2p - json

This is my code
bids = response.json()["data"]["adv"]
NameError: name 'response' is not defined[enter image description here][1]
I don't understand how to get to the price, please explain, thank you
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "123",
"content-type": "application/json",
"Host": "p2p.binance.com",
"Origin": "https://p2p.binance.com",
"Pragma": "no-cache",
"TE": "Trailers",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"
}
data = {
"asset": "USDT",
"fiat": "RUB",
"merchantCheck": False,
"page": 1,
"payTypes": ["TinkoffNew"],
"publisherType": None,
"rows": 1,
"tradeType": "SELL"
}
r = requests.post('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', headers=headers, json=data)
print(r.text)
def main():
bids = response.json()["data"]["adv"]
for item in adv:
price = item["price"]
return f"{bids}"
if __name__ == "__main__":
main()
[1]: https://i.stack.imgur.com/yk0ML.png

You got few things going here:
You're saving the response to a variable called r, not response, so it is not defined.
You're doing nothing with price (not sure if it's just stayed in your example code or not).
r.json()["data"] returns a list (an array), which means you'll need to choose a numeric index to access adv.
e.g.
import requests
headers = {...
data = {...
r = requests.post(
'https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', headers=headers, json=data)
print(r.text)
def main():
val = r.json()["data"][0]["adv"] # notice im referring 'r' and im adding the [0] index before ["adv"]
print(val)
if __name__ == '__main__':
main()

Related

POST request can't pass body data from python

i am trying to post a request with body to flask REST-api but it doesn't work (Error Response 500), but when i am trying to post it from POSTMAN it works.
body = {
"content_type": "test",
"dc":{
"title": " test",
"is_top": "test",
"position": 0,
"status" : "test"
}
}
headers = {
'Content-Type': 'application/json', 'Accept': 'text/plain'
}
response = requests.post(url, headers = headers, data=body)
i tried with json.dump() also but it was the same result.
POSTMAN CODE (python) that works:
payload = "{\r\n \"content_type\": \"test\",\r\n \"dc\":{\r\n \"title\": \" test\",\r\n \"is_top\": test,\r\n \"position\": 0,\r\n \"status\" : \"test\"\r\n }\r\n }"
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)
Try this:
body = {
"content_type": "test",
"dc": {
"title": " test",
"is_top": "test",
"position": 0,
"status": "test"
}
}
resp = requests.post(url, json=body)
resp.raise_for_status()
instead json.dump use json.dumps
import requests
import json
postData = { "id" : 1 , "limit":False, "list":[1,2,3] }
response = requests.post("https://abc/api/method",data=json.dumps(postData))
print(json.loads(response.content)

Upload data to server Retrofit 2

i use com.github.ChiliLabs:ChiliPhotoPicker:0.3.1 to select photos to upload. It gives me such a path to the photo
file:///storage/emulated/0/KatePhotos/1641933129.jpg
my code for uploading the image to the server
fun formData(uri: ArrayList<Uri>) {
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://httpbin.org")
.build()
// Create Service
val service = retrofit.create(APIService::class.java)
// List of all MIME Types you can upload: https://www.freeformatter.com/mime-types-list.html
// Get file from assets folder
val imgFile = File(uri[0].path)
val fields: HashMap<String?, RequestBody?> = HashMap()
fields["email"] = ("test#test.com").toRequestBody("text/plain".toMediaTypeOrNull())
val filename = imgFile.name
fields["file\"; filename=\"$filename\" "] =
(imgFile).asRequestBody("image/*".toMediaTypeOrNull())
CoroutineScope(Dispatchers.IO).launch {
// Do the POST request and get response
val response = service.uploadEmployeeData(fields)
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
// Convert raw JSON to pretty JSON using GSON library
val gson = GsonBuilder().setPrettyPrinting().create()
val prettyJson = gson.toJson(
JsonParser.parseString(
response.body()
?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
)
)
println(prettyJson)
} else {
Log.e("RETROFIT_ERROR", response.code().toString())
}
}
}
}
The problem is that when I use decoding on the server, I only get a piece of the image. Tell me what I'm doing wrong and how can I fix it?
Its my response:
{
"args": {},
"data": "",
"files": {
"file": "data:image/*;base64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5Fpo0726+WrxxSyzPDJdGEgKzuYHA3PhWl8Jfsc/ETxp8T9U+FWg+I/Cl/rkOn6fqtleWllq97ZarZ3kcckE8cttYymCIrPFmS6WBELYYrhsdyb2as9dOul77dbpr5O2zOCy3T07+trP096Ovmr7nyT9aK+qfG/wNgtfg18OvHGgW2m2Ou23h251TxNbvczPcXmNfutOWeJPmjCx7bSJgpT76sA2XYZOofs2XmmaT8Rry7+LPwqj13wrHH/aujquqtcidzGi2scosfsz3BlkaLy/Ozuimb7kbOKi7tqOtm162dtO/wAipQafK9H+vZ9j5s+lFfTXxv8A2Tvit+z/AOHdF8RePba3jtbq7/s6ZI7HUIPsN35XmeUZbm2hhueBJ+8tJJ4sxn58FC3zL+lTGabaT2/r8tfTUlJ2Uuj/AOGA5FGfev0T8N/CL4Zr+zl4M8deI/hv4Ol0q68Ha7quteKI9fujrun6kmoXdpp5h0xLvY1s0yWMDSNaGMeY26VG5GJ8Nf2EvHmo3XwY8UfEW7s/D3w88Qapoq3wax1VJILG+lQQlbwWTWbyzB4o1SKaR43nTzVjVZWj1jD966T6O1+l25K3e/ut7bNPqZynaDn2u7dbJJt9utt99D4HoHp2r7HuP2btS+LviL43698ID4EsfDPhiS6k+waTZeIpbM28Fu8pMd7dWsiRMywygC8nhLyBgg2lBWR8Of2atM1fx98F/CfxJ+KPgjwbe+KNR0oTaChv31e3sLxlaKTfFZTWsUksbRmNXkLKZojIqLuK5UJ+05
},
"form": {
"email": "test#test.com"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "387553",
"Content-Type": "multipart/form-data; boundary\u003da3942d3b-e13b-43de-9abd-642750914c37",
"Host": "httpbin.org",
"User-Agent": "okhttp/4.9.0",
"X-Amzn-Trace-Id": "Root\u003d1-61ddfc53-4b83816821e2302e6f2b8951"
},
"origin": "",
"url": "https://httpbin.org/post"
}
and so I see what php saves, even notepad considers it to be text.
In decode i see

Post List <int> in http Flutter

I want to send a data like this :
{
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212]
}
To api in flutter. I tried to do that
var data = {
"year": selectedYear,
"class": _classController.text.toString(),
"files": json.encode(carfilesids),
};
final response = await http.post(url, body: data,headers:
{'Accept': 'application/json'});
However there's no errors in run time and when I print the value of json.encoder.convert(carfilesids) it gives me List, I got a response status code of 422 and it tells me " {"message":"The given data was invalid.","errors":{"files":["The files must be an array."]}} ". I also tried to json.encode the whole data but it goes wrong with the other data attributes.
You must use jsonEncode on your map, or else the http package will treat it as form data.
From the documentation:
If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
final response = await http.post(url,
body: {
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212 ]
},
headers: {
'Accept': 'application/json'
}
);

How to make GET requests works in Postman and Google Apps script

The following works in Postman:
GET https://mainnet.incognito.org/fullnode
with Body -> raw of:
{
"id": 1,
"jsonrpc": "1.0",
"method": "getbeaconbeststatedetail",
"params": []
}
The following doesn't work in Google app scripts:
function getBeaconState() {
const mainnet = "https://mainnet.incognito.org/fullnode";
var raw = JSON.stringify({ "id": 1,"jsonrpc": "1.0","method": "getbeaconbeststatedetail","params": []});
var requestOptions = {
"method": "get",
"headers": {"Content-Type": "application/json"},
"body": raw,
"redirect": "follow"
};
var beaconState = UrlFetchApp.fetch(mainnet, requestOptions);
Logger.log("I set the beaconState variable.");
}
It gets a 400 error, so it must be something I'm doing wrong but poking around hasn't gotten me very far.

Content Type of POST request payload

I am sending a JSON body in my POST Request, but http.DetectContentType is identifying it as a text/plain type.
I want to have flexibility to process request payload based on their content type - if XML {} if JSON {} else {NO Processing}
To achieve this conditional processing, I am using http.DetectContentType to return the content type o the request but it is returning text/plain is every scenario.
func Test(w http.ResponseWriter, r *http.Request) *ErrorObject {
reqBuffer := make([]byte, 512)
_, err := r.Body.Read(reqBuffer)
if err != nil {
return ErrorObject{}.New(1, err, nil)
}
contentType := GetContentType(reqBuffer)
fmt.Printf(contentType)
if contentType == "application/xml" || contentType == "text/xml" {
w.Header().Set("Content-Type", "application/xml; charset=UTF-8") ...}
if contentType == "application/json" || contentType == "text/json" {
w.Header().Set("Content-Type", "application/json; charset=UTF-8") ... }
else return Invalid Request Type error
}
func GetContentType(buffer []byte) string {
fmt.Println(string(buffer))
contentType := http.DetectContentType(buffer)
fmt.Printf(contentType)
return contentType
}
Expect to return the function - Content Type as application/json but getting text/plain
Using POSTMAN to send request to server with Body as raw and JSON
{
"data": [
{
"group": "TEST",
"name": "TEST",
"released": true,
"version": 1,
"teststeps": [
{
"bin": 32,
"comment": "PAA",
"dataType": "J",
"format": "R6.2",
"id": "PAA3",
"osg": 8,
"usg": 0
}
],
"parameters": [
{
"comment": "test",
"description": "test",
"format": "R7.0",
"id": 1,
"teststepId": "PAA",
"value": 30,
"type": "teststep"
}
]
}
]
}
I am using http.DetectContentType to return the content type o the request but it is returning text/plain is every scenario.
According to the documentation DetectContentType "... implements the algorithm described at https://mimesniff.spec.whatwg.org/ to determine the Content-Type of the given data". The algorithm there is primarily for handling content types which the browser can handle by itself.
And if you look at the actual code you'll see that it does not care about application/json or similar at all and that it returns text/plain for anything which looks non-binary (and was not matched before as with text/html).
In other words: this is the wrong tool for the job. The proper way would be for the client to specify what kind of content is sent using the Content-Type header and not to let the server guess the kind of content.