Trying to send a dynamic payload (python) - python

I have been trying to make a POST request. My code is working properly if I put the "contestId" manually, but I want to make it dynamic.
payload = "{\"contestId\":\"dcaf641d-ff39-4bf9-b295-4eb13936410d\",\"contestType\": \"OverUnder\",\"direction\": \"moon\",\"wager\": \"1\"}"

Use some string concatenation to insert the variable holding the contestID into the right position.

Your payload is json, therefore use json:
contest_id = "dcaf641d-ff39-4bf9-b295-4eb13936410d"
payload = {"contestId": contest_id, "contestType": "OverUnder", "direction": "moon", "wager": "1"}
response = request.post(URL, json=payload, headers=headers, params=querystring)

Related

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!

User Input Based Requests Python

I am making a post request and I have a payload variable but I am trying to set some of the data in the payload variable as user input so I am doing:
payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}".format(name, pass)
I get this error:
File "testing.py", line 24, in sndReq
payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}".format(name, pass)
KeyError: '\r"user"
If I take out .format and put hard values in there it works. (I also tried using an 'f' string)
My request line is this if it matters:
r = requests.request("POST", url, data=payload, headers=headers)
It seems your string is not formatted/escaped properly. How about doing something which is more readable, such as:
import requests
# some example values because your question doesn't give too many details
user, password ="user", "password"
url="http://google.com" # example url
headers={'pragma': 'no-cache'} # whatever your headers are
# now do the request, note we're not passing a single string here
requests.post(
url,
json={
"user": user,
"password": password
},
headers=headers
)
Additionally, I'd encourage you to work with something a bit easier than those unreadable strings! Put it into something that python (and us) can work with more easily. The first thing I'd do is get your string into a python object:
import json
payload = "{\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r}"
data=json.loads(payload)
data.update({'password': 'secret', 'user': 'me'})
# {u'password': 'secret', u'user': 'me', u'gdn': 0}
And finally, if you truly want to use the {} as the format string (which I hope the rest of my answer shows you is much more difficult than you need to make it), you'll need to remove the leading and trailing braces in the formatted text:
"{" + "\r\"user\": \"{}\",\r\"password\": \"{}\",\r\"gdn\": 0\r".format("user", "secret") + "}"
# '{\r"user": "user",\r"password": "secret",\r"gdn": 0\r}

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

Sending json post request with python

With the firefox plugin "HttpFox" i'm getting the POST request which looks like this:
{'json':'{"command":"SEARCH","data":{"someData":"someValue","otherData":"otherData"}}'}
Now i need to send a http request build with python to get the same data as i would get via browser. See code:
headers = {'Content-type': 'application/json; charset=utf-8'}
payload = ?
req = requests.post(url, data=json.dumps(payload), headers = headers)
My problem is:
I'm not sure how to build the payload. It should be a dictionary as well, but im confused because of the POST type which is delivered with HttpFox. There are two dictionaries inside the main dictionary.
How should i handle this ?
Appreciate any help.
Ok, i found the solution:
It was necessary to build a dict like this:
valueString = """{"command":"SEARCH","data":{"someData":"someValue","otherData":"otherData"}}"""
/// the """ ensures that the whole text between """ is handled as a string.
payload = {'json': valueString}
The key 'json' requieres a string. In this case the string looks like a dictionary.
That's it.

How do I make a GET request with JSON in the request body

I need to send this JSON array in a GET request
{"user": "jähn", "id": 3}
I tried to use
data = '{"user": "jähn", "id": 3}'
headers = {
'Content-type': 'application/json',
'Accept': 'text/plain'
}
request = urllib.request.Request(self.update_url, data=data,
headers=headers, method='GET')
response = urllib.request.urlopen(request)
But its failing with: TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
Another thing that I find quite weird is that it tells me about POST data although I set the method on the Request to GET.
Since this is a simple script I'd prefer not to use a library like python-requests
You cannot make a GET request with a JSON-encoded body, as a GET request only ever consists of the URL and the headers. Parameters are encoded into the URL using URL encoding instead, there is no option to encode such parameters to JSON instead.
You create URL-encoded parameters with the urllib.parse.urlencode() function, then appended to the URL with ?.
from request.parse import urlencode
data = {"user": "jähn", "id": 3} # note, a Python dictionary, not a JSON string
parameters = urlencode(data)
response = urllib.request.urlopen('?'.join((self.update_url, parameters)))
Do not use the data parameter; using that keyword argument forces a request to use the POST method:
data must be a bytes object specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format.

Categories