Call an API with python - json

I used Postman to get a bit more info and have used the snippet of code to run the request it is working now but i still want the request to print in JSON not in text im really stuck.....
import requests
url = "https://ice3x.com/api/v1/stats/marketdepthfull/"
headers = {
'cache-control': "no-cache",
'postman-token': "afb97efe-aaf1-cdae-004f-29aac565780a"
}
response = requests.request("GET", url, headers=headers)
print(response.text)
The result i get is:-
{"errors":false,"response":{"entities":[{"pair_id":"3","min":"56600.00000000","max":"59600.00000000","avg":"58547.48550813","vol":"5.68526617","pair_name":"btc/zar","last_price":"58547.00000000"},{"pair_id":"4","min":"0.00000000","max":"0.00000000","avg":"0.00000000","vol":"0.00000000","pair_name":"btc/ngn","last_price":"1560000.00000000"},{"pair_id":"6","min":"732.00000000","max":"781.00000000","avg":"765.97099358","vol":"160.77519562","pair_name":"ltc/zar","last_price":"760.00000000"},{"pair_id":"11","min":"4050.00000000","max":"4349.00000000","avg":"4253.33493584","vol":"74.22964491","pair_name":"eth/zar","last_price":"4230.00000000"},{"pair_id":"12","min":"0.00000000","max":"0.00000000","avg":"0.00000000","vol":"0.00000000","pair_name":"eth/ngn","last_price":"110000.00000000"}]},"pagination":{"items_per_page":1000,"total_items":5,"current_page":1,"total_pages":1}}
Process finished with exit code 0
What i need is to be able to dump the json and call it again if i need it
Please help

Related

Google scripts, using urlFetchApp() for PUT request, I cannot get a response code when server sends 204 no content response

For GET and POST requests for a private server I work with I use in Google Sheets, do something like this, and I get a proper response. I use that response to update data and just as importantly for error checking by evaluating response.getResponeCode().
function postDataToServer(params){
let myjdService = getService();
let orgId = getOrgIdForSelectedOrg();
let link = https://GoodURLForPrivateDataIWorkWithALot/neededurlParameter/anotherNeededURLParameter;
let options = {
'method': 'put',
'payload': JSON.stringify(params),
'headers': {
'Accept': 'application/vnd.PRIVATE.v3+json',
'Content-Type': 'application/vnd.PRIVATE.v3+json',
'authorization': 'Bearer ' + myPrivateService.getAccessToken()
}
};
let response = UrlFetchApp.fetch(link, options);
return response.getResponseCode();
For all the GET and POST requests I do, I get a response. And from that response I can parse a response code. But for the specific server I work with, when I edit a record using PUT, a successful edit returns this:
204 No Content
And further, the last line return response.getResponseCode() returns an error the response is undefined.
Here's the error I get for doing anything with response:
ReferenceError: response is not defined
The PUT is working. I only know this because 1) when I check if edits are made with the server, they are 2) testing the PUT in Postman at least shows me the words "204 No Content" and 3) the documentation says that's exactly what I should expect.
But I still would like to find out how to evaluate this no-content response in my Google Sheets App for proper error tracking. At least some way to get the string "204". Any ideas? I can't even get Google Sheets to do say 204.

Flask API can receive posts from AJAX but not Postman

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.

Send json data for json get request in odoo 12

I want send json data from odoo controller.For that i have created below controller
from odoo.http import Response
import json
#http.route('/api/json_get_request',auth='public',type='json',methods=["GET"],csrf=False)
def printjson(self,**kw):
headers={'content-type':'application/json'}
return Response(json.dumps({"test":"json string"}),headers=headers)
but accessing http://localhost:8089/api/json_get_request in postman gives me Invalid json data then I have check postman console in that response header -> Content-Type: "text/html" is shown.
Not understand after sending data in the json type why json data not recieved.
After accessing http://localhost:8089/api/json_get_request as http request on postman gives me correct json data.
Please give me suggestion
Thanks in advance
First thing method that handle 'json' request should return a dictionary directly:
#http.route('/api/json_get_request', auth='public', type='json', csrf=False)
def printjson(self, **kw):
return {'attribute': 'test'}
this will return a result like this:
{
"jsonrpc": "2.0",
"id": null,
"result": {
"attribute": "test"
}
}
You are having this error because you didn't send any json data with the request.
You could test your code using the requests module:
>>> import requests
>>> import json
>>> url = 'http://localhost:8069/api/json_get_request'
>>> data = {'params': {'test': 100}}
>>> headers={'content-type':'application/json'}
>>> requests.get(url, data=json.dumps(data), headers=headers)
<Response [404]>
It gives me this error because there is no database selected, and I have more than one database.
If you have only one database you see the correct result.
but when you test it from Postman extension I used RESTED
Because I'm all ready logged to Odoo the method was executed successfully , Just look for a better postman extension or search how to send json data with your current postman. You need to send some json data in the request.

Not able to capture previous API response and append the response in URL of Post Request API

I am trying to POST API request where I am getting API response as
"d": {
"__metadata": {
"uri": "http://ev-qa02.zs.local/IncentiveManager/0002i1/wcf/v5.svc/InDataRequestCreators('9f31c6da-ec56-4360-8589-d21b6320f99b')",
"type": "ZSAssociates.Javelin.ETL.Rest.v5.InDataRequestCreator"
},
"ScenarioId": "9f31c6da-ec56-4360-8589-d21b6320f99b",
"CallbackUrl": "",
"DataExpiresOnUtc": "/Date(4103913600000)/",
"CreateScenarioIfMissing": false,
"AdapterId": "0fcbd8d2-f5cb-4e2a-bda8-bb37037b022d",
"InDataRequestIdOut": "eb36f8a9-5b7d-4835-88f6-4af67830c1e9",
"InDataRequestUrlOut": "/InDataRequests('eb36f8a9-5b7d-4835-88f6-4af67830c1e9')"
}
}
Now I am trying to hit another API request where my URL would be kind of
http://ev-qa02.zs.local/IncentiveManager/0002i1/WCF/V5.svc/InDataRequests('eb36f8a9-5b7d-4835-88f6-4af67830c1e9')/FileCreator
*InDataRequests('eb36f8a9-5b7d-4835-88f6-4af67830c1e9') This random number is generated from above response value "InDataRequestIdOut"
How can I append the URL taking previous API response and adding in my 2nd POST request.
I am not able to capture my response and used it in other API POST request? i would realy appreciate if you can help me here,been stuck in this issue since couple of days,I went through doc and examples too but couldn't resolve this.I have attached screenshot too.PostUrlFailureScreenshot
My main problem is line number 26 and 27 from eclipe screenshot
Scenario: Verify that JIM Idr request ofr Post
Given header Content-Type = 'Application/JSON'
And header Accept = 'Application/JSON'
And header Authorization = 'Basic
UUEwMl9JbmNlbnRpdmVNYW5hZ2VyXzAwMDJpMTpZWkxaRjlGclR1eWhlcVNJbXlkTlBR'
Given path 'InDataRequestCreators'
* def user =
"""
{
"ScenarioId":"9f31c6da-ec56-4360-8589-d21b6320f99b",
"AdapterId":"0fcbd8d2-f5cb-4e2a-bda8-bb37037b022d",
"DataExpiresOnUtc":"2100-01-18T00:00:00",
"CreateScenarioIfMissing":"false"
}
"""
And request user
When method post
Then status 201
* print 'the value of response is:', response
And def app = response
And path 'app.InDataRequestIdOut' + '/FileCreators'
* def body =
"""
{
"InDataRequestId": "1d6326a2-d25f-41d2-9303-8a6e6101efcc",
"ProcedureName": "",
"SourceWorkspacePath": ""
}
"""
And request body
When method post
Then status 201
First, it looks to me you are using the wrong Eclipse plugin for Cucumber, please refer to this issue and make sure: https://github.com/intuit/karate/issues/90
There are so many things you are doing wrong. For example it should be application/json (lowercase). There are many places you are mixing upper case and lower case in your above description, please take care.
And there is no way to understand how the URL is being set up, without this - I can't provide proper help.
You have a fundamental misunderstanding of how to use Karate expressions, for example this is just concatenating two strings:
And path 'app.InDataRequestIdOut' + '/FileCreators'
This may give you some hints, instead of the above:
When url baseUrl
And path "InDataRequests('" + response.InDataRequestIdOut + "')/FileCreator"
And is it FileCreator or FileCreators. You seem to be quite careless :(

Want to receive json response for GET request. Postman gives me the json data. But when I do it programatically it returns empty html

import requests
import json
#Infrastructure API URL
url = "http://10.39.188.69/server-manager/tomcat/bimws/rest/v1/infrastructures/?format=json"
myResponse = requests.get(url, headers=headers, verify=False)
print myResponse
print(myResponse.status_code)
#print(myResponse.text)
print(myResponse.json)
Output i get:
c:\automation>python rest_API.py
C:\Python27\lib\site-
packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding
certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/late/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
C:\Python27\lib\site-packages\requests\packages\urllib3\connectionpool.py:852:
nsecureRequestWarning: Unverified HTTPS request is being made. Adding certifica
e verification is strongly advised. See: https://urllib3.readthedocs.io/en/late
t/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
<Response [200]>
<bound method Response.json of <Response [200]>>
Try doing myResponse.json(). myResponse.json returns an instancemethod type while myResponse.json() will return the json data.