Hi I am trying to extract information from this API endpoint: https://graphql.icy.tools/graphql
Im trying to fetch the trending collections as shown here: https://docs.icy.tools/developer-api/common-use-cases/fetch-trending-collections
To do so Im just using this simple code:
import requests
import json
url = "https://graphql.icy.tools/graphql?query=TrendingCollections"
response= requests.get(url)
print(response.text)
However after running it I just get an error in form of a json.
Is this because the parameter TrendingCollections is not recognized by the API, if so does someone know whats the actual value that I need to use?
Thanks!
import json
import requests
# Define the endpoint URL
endpoint = "https://graphql.icy.tools/graphql"
# Define the query
query = """
query TrendingCollections {
trendingCollections(orderBy: SALES, orderDirection: DESC) {
edges {
node {
address
... on ERC721Contract {
name
stats {
totalSales
average
ceiling
floor
volume
}
symbol
}
}
}
}
}
"""
# Make the POST request to the endpoint
response = requests.post(endpoint, json={'query': query})
# Parse the JSON response
data = json.loads(response.text)
# Print the data
print(data)
This code made with python worked and retrieved all data!
Related
I would like to know how to scrape data (position, name of the trader, symbol,..)from the Binance leaderboard with Python and Binance API.
Thanks for your answers !
This is my actual code wiche doesn't work.
from binance.client import Client, AsyncClient
api_key = 'xxx'
api_secret = 'xxx'
client = Client(api_key, api_secret)
leaderboard = client.futures_leaderboard()['positions']
I tried the code juste above, but there is no results.
You can use this third party API. Remember to check its documentation.
Here is an example of code to achieve what I think you want:
Getting traders:
import requests
# API URL with its endpoint to use
url = "https://binance-futures-leaderboard1.p.rapidapi.com/v2/searchLeaderboard"
# Parameters to use
querystring = {
"isShared": True, # Set to true if you want to get traders sharing their positions
"limit": 10 # Total traders to get
}
# Headers to use
headers = {
"X-RapidAPI-Key": "YOUR-API-KEY",
"X-RapidAPI-Host": "binance-futures-leaderboard1.p.rapidapi.com"
}
# Get response
response = requests.get(url, headers=headers, params=querystring)
# Print response to JSON
print(response.json())
Getting trader positions:
import requests
# Now we use the endpoint to get the positions shared by a trader
url = "https://binance-futures-leaderboard1.p.rapidapi.com/v2/getTraderPositions"
# Parameters to use
querystring = {
"encryptedUid": "<REQUIRED>", # Trader UUID
"tradeType": "PERPETUAL" # Set to PERPETUAL to get USDⓈ-M positions
}
# Parameters to use
headers = {
"X-RapidAPI-Key": "YOUR-API-KEY",
"X-RapidAPI-Host": "binance-futures-leaderboard1.p.rapidapi.com"
}
# Get response
response = requests.get(url, headers=headers, params=querystring)
# Print response to JSON
print(response.json())
You have to fill in the api key and secret
How to Create API
Creating an API allows you to connect to Binance’s servers via several
programming languages.
I am new to python and want to fetch data from an API via Google Cloud Functions so that I can store the data in Google Cloud Storage afterwards.
The data is available in JSON format and I want to transform it in a table via pandas.
Since I am really unsure about the correct syntax I'd like to know how I have to call the function test_topic - The following code doesn't work for me. I get no error message but also I get no result.
What do I have to do that I get the table as a result?
import requests
import pandas as pd
def test_topic(df):
url = "https://api.domain.com/v1/"
payload={}
headers = {}
parameters = {
"api_key": "1234567890",
"start_date": "2020-01",
"end_date": "2021-01",
"format": "json"
}
response = requests.request("GET", url, headers=headers, data=payload, params=parameters)
df = response.json()['visits']
pd.DataFrame(df)
Your first issue is that you probably need to authenticate your request against the Cloud Function. Unless the Cloud Function was deployed --allow-unauthenticated (permitting anyone), you're going to have to authenticate requests using an access (?) token (TOKEN):
token = os.getenv("TOKEN")
headers=["Authorization"] = "Bearer: {token}".format(token=token)}
For development purposes, you can grab a token using gcloud and export this to your code:
export TOKEN=$(gcloud auth print-access-token)
python3 main.py
You should also:
headers["Accept"] = "application/json"
For debugging, you should consider:
json_response = response.json()
print(json_response)
before you try to access visits, perhaps:
if "visits" in json_response:
# JSON response contains "visits"
else:
# JSON response does not contain "visits"
I'm trying to use requests API to login into Zabbix API, but unable to do due to the below issue.
I want to achieve the login by pyzabbix module, but I want to use API user authentication token.
Without password and username in the code (any suggestion would help me).
Error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Code:
import requests
from pprint import pprint
import json
url = 'http://127.0.0.1/zabbix'
########################################
# user.login
########################################
payload = {
"jsonrpc" : "2.0",
"method" : "user.login",
"params": {
'user': 'Admin',
'password':'Zabbix',
},
"auth" : None,
"id" : 0,
}
headers = {
'content-type': 'application/json',
}
res = requests.post(url, data=json.dumps(payload), headers=headers)
print(res)
res = res.json()
print('user.login response: ',res['result'])
If you want to call the Zabbix API you have to use the correct endpoint, which is api_jsonrpc.php.
So, for instance you can use:
url = 'http://127.0.0.1/api_jsonrpc.php'
However your code does not account for errors (ie: if Admin/Zabbix is wrong, your script will return a key error, because the error response does not contain a result.
A better choice is to use a library such as py-zabbix
I'm in the process of moving learning how to interact with APIs in my programming training. The following script is used on the sandbox environment for a software I'm trying to interact with.
For some reason, I cannot login to the API to run the second function. Does anyone see the issue?
# import requests library
import requests
#import json library
import json
controller='apicontroller#test.com'
def getToken():
# put the ip address or dns of your apic-em controller in this url
url = "https://" + controller + "/api/aaaLogin.json"
json_object = {
"aaaUser" : {
"attributes" : {
"name" : "******",
"pwd" : "*******"
}
}
}
#Content type must be included in the header
header = {"content-type": "application/json"}
#Performs a POST on the specified url to get the service ticket
response= requests.post(url,data=json.dumps(json_object), headers=header, verify=False)
#convert response to json format
r_json=response.json()
#parse the json to get the service ticket
token = r_json["response"]["token"]
return token
def pushtenant():
# URL for network device REST API call to get list of existing devices on the network.
url = "https://" + controller + "/api/api/mo/uni"
#Content type must be included in the header as well as the ticket
headers = {"content-type": "application/json", "X-Auth-Token":Token}
json_tenant = [{
"fvTenant" : {
"attributes" : {
"name" : "ExampleCorp"
}
}
}]
# this statement performs a GET on the specified network-device url
response = requests.post(url, json.dumps(json_tenant), headers=headers,verify=False)
# json.dumps serializes the json into a string and allows us to
# print the response in a 'pretty' format with indentation etc.
print ("Response = ")
print (json.dumps(response.json(), indent=4, separators=(',', ': ')))
enter code here
#convert data to json format.
r_json=response.json()
theToken=getToken()
pushtenant(theToken)
I'm trying to retrieve the response json data by a web site that I call.
The site is this:
WebSite DriveNow
On this page are shown on map some data. With browser debugger I can see the end point
end point
that sends response data json.
I have use this python to try scrape the json response data:
import requests
import json
headers = {
'Host': 'api2.drive-now.com',
'X-Api-Key': 'adf51226795afbc4e7575ccc124face7'
}
r = requests.get('https://api2.drive-now.com/cities/42756?expand=full', headers=headers)
json_obj = json.loads(r.content)
but I get this error:
hostname doesn't match either of 'activityharvester.com'
How I can retrieve this data?
Thanks
I have tried to call the endpoint that show json response using Postam, and passing into Header only Host and Api-Key. The result is the json that i want. But i i try the same call into python i recive the error hostname doesn't match either of 'activityharvester.com'
I don't understand your script, nor your question. Why two requests and three headers ? Did you mean something like this ?
import requests
import json
headers = {
'User-Agent': 'Mozilla/5.0',
'X-Api-Key':'adf51226795afbc4e7575ccc124face7',
}
res = requests.get('https://api2.drive-now.com/cities/4604?expand=full', headers=headers, allow_redirects=False)
print(res.status_code, res.reason)
json_obj = json.loads(res.content)
print(json_obj)