Python requests_Query_String_Multiple_Values - python-requests

I am trying to request REST API as below
querystring = {"severity":'medium'}
headers = {"Accept": "application/json"}
response = requests.request("GET", url, headers=headers, params=querystring)
Question:I want to get some data with multiple severity values in query string. As of now I can pass only a single value.After trying querystring = {"severity":['medium','high']} , got only the medium severity events.
Help please.

Related

How to fix my function to obtain track ID by searching with Spotify API?

I would like to obtain the track ID from Spotify by searching with the track name. I have set up my Spotify developer account and am using spotipy. I found people with similar issues (Correct python syntax to search by artist in Spotify's Search API?) but cannot find any major differences between my code and the answers they received.
Here is my function. I am not getting any error messages, but it keeps returning "None." What should I change?
def get_id(track_name:str, token:str) -> str:
headers = {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Bearer {tokenjson}'.format(tokenjson=auth_token)
}
params = {
'q':track_name,
'type':'track'
}
try:
response = requests.get('https://api.spotify.com/v1/search',
headers = headers,
params = params
)
json = response.json()
first_result = json['tracks']['items'][0]
track_id = first_result['id']
return track_id
except:
return None

PostgREST returns no error with wrong JSON values (Python request)

I'm trying to make a client for postgREST (latest version with PostgreSQL 13)
When I tried to insert data, I felt on (what seems to me) a strange behavior: when I use json.dumps for an insert request, event if my value are wrong, I get a 201 code in response.
Working code
The field id is a primary key.
headers["Authorization"] = mytoken
myjson = {"id": "13", "name":"nameinserted"}
r = requests.post(url, json=myjson, headers=headers)
Returns a 201 code
If I retry that code, I get a 409 (which is normal)
Not working code :
This one always returns me a 201 code, and never insert something in database (even with correct data).
The difference is json.dumps(myjson) that I used by mistake.
headers["Authorization"] = mytoken
myjson = {"id": "13", "name":"nameinserted"}
myjson = json.dumps(myjson)
r = requests.post(url, json=myjson, headers=headers)
Why don't I get an error about data or malformed json?
In the first example you gave, the JSON encoded payload sent to PostgREST is:
'{"id": "13", "name": "nameinserted"}'
In the second example, after encoding it once again, the payload sent is:
'"{\\"id\\": \\"13\\", \\"name\\": \\"nameinserted\\"}"'
PostgREST parses the first payload as a JSON value; on the other hand, the second payload is parsed as a String value, equivalent to '"any_string"' for example. PostgREST is lenient with this type of payload and doesn't give an error but defaults it to an empty JSON array '[]', which is allowed even if the array is empty due to bulk insertion, and responds with a 201.

Web2py: Sending JSON Data via a Rest API post call in Web2py scheduler

I have a form whose one field is type IS_JSON
db.define_table('vmPowerOpsTable',
Field('launchId',label=T('Launch ID'),default =datetime.datetime.now().strftime("%d%m%y%H%M%S")),
Field('launchDate',label=T('Launched On'),default=datetime.datetime.now()),
Field('launchBy',label=T('Launched By'),default = auth.user.email if auth.user else "Anonymous"),
Field('inputJson','text',label=T('Input JSON*'),
requires = [IS_NOT_EMPTY(error_message='Input JSON is required'),IS_JSON(error_message='Invalid JSON')]),
migrate=True)
When the user submits this Form, this data is also simultaneously inserted to another table.
db.opStatus.insert(launchId=vmops_launchid,launchDate=vmops_launchdate
,launchBy=vmops_launchBy,opsType=operation_type,
opsData=vmops_inputJson,
statusDetail="Pending")
db.commit()
Now from the scheduler, I am trying to retrieve this data and make a POST request.
vm_power_opStatus_row_data = vm_power_opStatus_row.opsData
Note in the above step I am able to retrieve the data. (I inserted it in a DB and saw the field exactly matches what the user has entered.
Then from the scheduler, I do a POST.
power_response = requests.post(vm_power_op_url, json=vm_power_opStatus_row_data)
The POST request is handled by a function in my controller.
Controller Function:
#request.restful()
def vmPowerOperation():
response.view = 'generic.json'
si = None
def POST(*args, **vars):
jsonBody = request.vars
print "Debug 1"+ str(jsonBody) ##-> Here it returns blank in jsonBody.
But if I do the same request from Outside(POSTMAN client or even python request ) I get the desired result.
Is anything going wrong with the data type when I am trying to fetch it from the table.
power_response = requests.post(vm_power_op_url,
json=vm_power_opStatus_row_data)
It appears that vm_power_opStatus_row_data is already a JSON-encoded string. However, the json argument to requests.post() should be a Python object, not a string (requests will automatically encode the Python object to JSON and set the content type appropriately). So, the above should be:
power_response = requests.post(vm_power_op_url,
json=json.loads(vm_power_opStatus_row_data))
Alternatively, you can use the data argument and set the content type to JSON:
power_response = requests.post(vm_power_op_url,
data=vm_power_opStatus_row_data,
headers={'Content-Type': 'application/json')
Also, note that in your REST POST function, request.vars is already passed to the function as **vars, so within the function, you can simply refer to vars rather than request.vars.

How to properly make POST request

I'm trying to make my first POST request to an API. For some reason, I always get status 403 in return. I suspect it's the signature that is being incorrectly generated. The api-key and client id is for sure correct.
My code
nonce <-as.integer(Sys.time())
post_message <- paste0(nonce, data_client.id, data_key) # data_client.id = client id # data_key = key
sha.message <- toupper(digest::hmac(data_secret, object = post_message, algo = 'sha256', serialize = TRUE))
url <- 'https://www.bitstamp.net/api/v2/balance/'
body = list('API-KEY' = data_key, 'nonce' = nonce, 'signature' = sha.message)
httr::POST(url, body = body, verbose())
Output
<- HTTP/1.1 403 Authentication Failed
I'm trying to access the Bitstamp API: https://www.bitstamp.net/api/?package=Rbitcoin&version=0.9.2
All private API calls require authentication. For a successful
authentication you need to provide your API key, a signature and a
nonce parameter.
API KEY
To get an API key, go to "Account", "Security" and then "API Access".
Set permissions and click "Generate key".
NONCEN
once is a regular integer number. It must be increased with every
request you make. Read more about it here. Example: if you set nonce
to 1 in your first request, you must set it to at least 2 in your
second request. You are not required to start with 1. A common
practice is to use unix time for that parameter.
SIGNATURE
Signature is a HMAC-SHA256 encoded message containing nonce, customer
ID (can be found here) and API key. The HMAC-SHA256 code must be
generated using a secret key that was generated with your API key.
This code must be converted to it's hexadecimal representation (64
uppercase characters).
I'm not sure if your question is still standing, but based on your code, I managed to get it working. In fact, the main problem is in the body, the API documentation shows it expects 'key' instead of 'API-KEY'.
Also, serialize should be FALSE instead of TRUE.
At the moment this works (but the API may change):
nonce <-as.integer(Sys.time())
post_message <- paste0(nonce, data_client.id, data_key) # data_client.id = client id # data_key = key
sha.message <- toupper(digest::hmac(data_secret, object = post_message, algo = 'sha256', serialize = FALSE))
url <- 'https://www.bitstamp.net/api/v2/balance/'
body = list('key' = data_key, 'nonce' = nonce, 'signature' = sha.message)
httr::POST(url, body = body, verbose())

POST data empty ( or not exist ) when I receive post back from TPV provider

I'm trying to implement a service Redsys payments on my .net website.
The payment is successful (data are sent by post) but when the POST data back to my website ( to confirm the payment ) and i try to retrieve them with:
Request.form string value = [ "name"]
the value is always empty
I tried to count how many are in Request.Form.Keys.Count and always gives me zero values.
In the vendor documentation it indicated that the variables may be collected with Request.form [ "name"] and I called them to ask why I do not get the data and they dont know why...so I'm desperate,
What may be due?
I have reviewed the header I get from the server ( width Request.Headers ) and have the following parameters. HttpMethod:: GET Requestype: GET and contentlength: 0 . My bank tell me that they response POST not GET... so it´s a mistery. May be the error is becouse that sendings are made from a https to a htttp ?
You are receiving a POST without parameters.
The parameters are in the content of the call.
You should read the content and get the values of each parameter:
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> PostNotification()
{
string body = "";
await
Request.Content.ReadAsStreamAsync().ContinueWith(x =>
{
var result = "";
using (var sr = new StreamReader(x.Result))
{
result = sr.ReadToEnd();
}
body += result;
});
In body you can read the parameters (the order of them can change).

Resources