Trying to sort in an API - python

im new in this of "Calling APIs", so i don't understand a lot, I was wondering if anyone can help me.
I want to sort the cryptocurrencies from coinmarketcap whit their API, in the Api documentation, says that there is a parameter 'sort', and i can use differents values, like 'name','symbol' and 'recently added'. So if i want to get the last cryptocurrency listed, i have to sort whit 'recently added'. But i dont know how to do it. Here is a piece of code that i can write, but whit that code i get All the cryptocurrencys and i dont know how to sort it. Thanks
import requests
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
parameters = {
'start':'1',
'limit':'5000',
'convert':'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'private key',
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
print(response.json())

I guess its
parameters = {
'start':'1',
'limit':'5000',
'convert':'USD',
'sort':'recently_added'
}
assuming you interpretted the docs right
it actually looks like it want 'sort':'date_added' NOT 'recently_added' based on the docs at https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest

Related

How to pass a parameter to the payload in a URL request (python)

(https://i.stack.imgur.com/xgoMx.jpg)
I want to be able to pass a variable through to where the registration plate (AA19AAA) is
Overall, I want a function to check the number plate, therefore I need to pass a parameter through the function and use it in the payload, but I'm not sure how to actually pass a string to the inside of the payload.
I have tried using .format(...) to add things to the string, concatenating the variable into the payload, and another method similar to .format(...). However, if you believe any of these could be applicable, please don't hesitate to tell me as I may have made a mistake somewhere.
I hope some of you can assist me in this, I'm sorry if there is an incredibly simple solution to this, but I have tried a few, and feel that it is time to ask the professionals.
Thank you so much
you have 2 options:
import requests
import json
payload = {'registrationNumber': some_var}
headers = {..., 'content': 'application/json'}
result = requests.post(url, headers = headers, data=json.dumps(payload))
or
import requests
headers = {...}
payload = {'registrationNumber': some_var}
result = requests.post(url, headers=headers, json=payload)

API Query Doesn't return results when "params" is encoded into a get request but API call works when URL isn't encoded

So when I access the API target via Postman with the URL below, it works fine without any issues
base_url = https://api.cats.net/orgs/CatEmpire/audit-log?phrase=action:stuck_on_tree+date_of_event:2022-01-11
However, when I append the below parameters into my request, the URL comes out differently and I'm no longer able to get results
parameters = {
'action:': 'stuck_on_tree',
'date_of_event:': '2022-01-11'
}
PAT = asdasdhdhdhhd123123
response = requests.get(base_url, headers={"Accept": "application/vnd.github.v3+json", "Authorization": f"Bearer {PAT}"}, params=parameters)
print(response.request.url)
#This returns https://api.cats.net/orgs/CatEmpire/audit-log?phrase=&action%3A=stuck_on_tree&date_of_event%3A=2022-01-11
I have tried to use:
paramters_string = urllib.parse.urlencode(parameters, safe='')
And then I updated my response variable below, but the results are still exaxtly the same. I have tried to do some digging but I can't seem to figure out if this an issue because I'm using a dictionary to pass the params, or if there's something else that I'm not able to understand. I'm fairly new to Python.
`response = requests.get(base_url, headers={"Accept": "application/vnd.github.v3+json", "Authorization": f"Bearer {PAT}"}, params=parameters)`
Your base URL should not include part of your query string (?phrase=).
Use this for your base URL:
https://api.cats.net/orgs/CatEmpire/audit-log
For your parameters, use this:
parameters = {
'phrase': 'action:stuck_on_tree+date_of_event:2022-01-11'
}
Update
Since you can't URL encode your parameters due to API constraints, you'll have to pass them as a string like so:
parameters = 'phrase=action:stuck_on_tree+date_of_event:2022-01-11'
have you tried ?
PAT = "asdasdhdhdhhd123123"
data = parameters
this is just an example of authorization request:
import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}
response = requests.post(endpoint, data=data, headers=headers)
So I figured it out. I needed to create a separate key for each parameter like below:
params = {
'phrase': 'action:stuck_on_tree',
'date_of_event:': '2022-01-11'
}
I'm not sure why I couldn't fit everything into the 'phrase' key, but this works and is also what I was trying to do to begin with because I wanted to be able to pass things dynamically into the params dictionary, so having all of my parameters in one key was going to be an issue. I didn't need to encode or unencode anything. Basically the semi colon was my issue lol. Thanks for all your help #dimz & #john glenn!

Understanding and Interacting with API using Python

I have a basic API installed as my localhost server that does functions such as add camera, star camera, list cameras, snapshot of camera frame, etc.
My problem is after following the documentation I still can't seem to interact with it well and get the response I need. Here is the code I use to log in and get validation token:
import requests
import urllib.request
import json
base_url = "http://localhostip:8080/api/user/login?"
parameters = {
"username": username,
"password": password
}
auth_tok = requests.post(base_url + urllib.parse.urlencode(parameters)).json()
print(auth_tok)
I get the correct documented response with a token, so following the documentation to add camera I need 2 parameters, URL and Name, so I did:
base_url = "http://localhostip:8080/api/camera/add?"
parameters = {
"url": 'rtsp://192.168.1.23/1',
#or video file
"url" : '/home/video/sample.mov'
"name" : 'cam1'
}
r = requests.post(base_url + urllib.parse.urlencode(parameters),headers={'Authorization': auth_tok})
when I print the response:
-print (r)
-print (r.url)
-print(r.status_code)
-print(r.json())
I get this:
<Response [500]>
http://192.168.0.162:8080/service/api/camera/add?url=rtsp%3A%2F%2Frtsp%3A%2F%2F192.168.1.23&name=cam1
500
{'code': -111, 'message': None}
According to documentation the correct url should be like this:
http://192.168.0.6:8080/service/api/camera/add?url=rtsp://192.168.1.23&name=cam1
and the response should be:
Response:
{"status":"ok"}
So why and how to make the URL POST in the correct format, because I suspect this is the issue, the URL has these encoding symbols that may be messing up the request?
When I use the web browser GUI of this API I can add the camera or even a video file to play but I'm trying to do the same with Python so I can do further processing in future.
Your problem is when you encode the ' / / ' symbol, so, in order to fix that, you need to use another function from urllib, urllib.parse.unquote(), and use as parameter your encoding function urllib.parse.urlencode(parameters):
import urllib
parameters = {
"url": 'rtsp://192.168.1.23/1',
"name" : 'cam1'
}
The results are :
print(urllib.parse.urlencode(parameters))
'url=rtsp%3A%2F%2F192.168.1.23%2F1&name=cam1'
print(urllib.parse.unquote(urllib.parse.urlencode(parameters)))
'url=rtsp://192.168.1.23/1&name=cam1'
Source https://docs.python.org/3.0/library/urllib.parse.html#urllib.parse.unquote

Using JSON data from API GET to POST to another API via python script

So, I'm new to python and am struggling, self taught, and still learning to code. So be easy on me :)
I am using a script to get data from one source (Jira's API) and trying to use those results to post to another (PowerBi).
I've managed to successfully get the data, I just don't know how to pass the data to this other API.
I know how to use the GET and POST calls, it's just using the data from one to another than I can't seem to find anything about. Assuming since what I'm asking for is very specific?
edit: I also want to mention that while my get is asking for specific data, I'm getting more than I actually need. So I need a way to specify (hopefully) what data is actually being sent to PowerBi's API
import json
import requests
url = 'https://mydomain.atlassian.net/rest/api/2/search'
headers = { 'Content-Type' : 'application/json',
'Authorization' : 'Basic 123456789' }
params = {
'jql' : 'project IN (, PY, CH, NW, RP, DP, KR, DA, RE, SS, CR, CD, AB) AND issueType=incident AND statusCategory!=Done',
'startAt': 0,
'maxResults' : 50,
}
requestget = requests.get(url, headers=headers, params=params)
if requestget.status_code == 200:
print(json.dumps(json.loads(requestget.text), sort_keys=True, indent=4, separators=(",", ": ")))
else:
print("None")
Apologies if I miss understood what you were asking help on, but you could use this to send a POST request as json.
request = urllib.request.Request()#Put the powerbi api here
request.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = #your json data
jsonBytes = jsondata.encode('utf-8')
#Has to be bytes
request.add_header('Content-Length', len(jsonBytes))
response = urllib.request.urlopen(request, jsonBytes)
You could go with a requests.post instead.
jsondata = #put json data here
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(jsondata), headers=headers)
Requests documentation

Formatting a nested json for use with Python Requests

I have been working on solving an HTTP 500 (bad syntax/string) error for far too long, and after doing some searching I cannot find a solution anywhere. I have a nested json PUT request that I have been able to make work using a couple API tools (both browser extensions and stand-alone programs), but when I try to use the json in Python's HTTP Requests module, I keep getting the 500 error code returned.
I have gotten other, simplier jsons (e.g. data={"RequestID": "71865"}) to work using similar code to the following, which leaves me to believe something is not getting formatted correctly, and I am unfortunately too new to this json-python thing to figure it out. I think the issue is because of the way python handles the nested json.
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import requests
import json
USER_NAME=u"myusername"
USER_PASS=u"mypassword"
PUT_URL="https://webservice.url.com/A/Path/To/Create/"
headers = {"Content-Type": "application/json"}
data = {
"ListOfFields": {
"Field": [
{"fieldname": "summary","value": "test summary"},
{"fieldname": "notes","value": "an example json PUT"},
{"fieldname": "user","value": "myuser"}
]
}
}
data_json = json.dumps(data)
payload = {'json_playload': data_json } ## I have tried with and without this line.
r = requests.put('{}'.format(PUT_URL), data=data_json, headers=headers, auth=(USER_NAME, USER_PASS), timeout=10)
# r = requests.put('{}'.format(PUT_URL), data=payload, headers=headers, auth=(USER_NAME, USER_PASS), timeout=10)
I have tried putting the data value into quotes, a single line, and making some other slight tweaks, but I keep getting the 500 error.
print(r.status_code)
>> 500
As mentioned before, I have gotten similar code to work in python using GET and POST and the same web server, but this one is giving me a headache!
The Requests library has a nasty habit of clobbering data when passing in nested JSON to the data param. To avoid this, pass it into the json param instead:
r = requests.put(PUT_URL, json=data_json, headers=headers, auth=(USER_NAME, USER_PASS), timeout=10)
For more details, take a look at this answer to a similar question: Post JSON using Python Requests
Do you want to pretty print your JSON data? Try this:
data_json = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
See https://docs.python.org/2/library/json.html

Categories