How to send a payload with python requests - python

So I understand the concept of sending payloads with requests, but I am struggling to understand how to know what to send.
for example, payload = {'key1': 'value1', 'key2': 'value2'} is the payload,
but how do I find what key1 is? Is it the element ID? I have worked closely to selenium and I am looking at requests at a faster alternative.
Thanks for your help, Jake.

Requests is a library which allows you to fetch URL's using GET, POST, PUT, etc requests. On some of those you can add a payload, or extra data which the server uses to do something.
So the payload is handled by the server, but you have to supply them which you do by defining that dictionary. This is all dependent on what the server expects to receive. I am assuming you read the following explanation:
Source
You often want to send some sort of data in the URL’s query string. If
you were constructing the URL by hand, this data would be given as
key/value pairs in the URL after a question mark, e.g.
httpbin.org/get?key=val. Requests allows you to provide these
arguments as a dictionary of strings, using the params keyword
argument. As an example, if you wanted to pass key1=value1 and
key2=value2 to httpbin.org/get, you would use the following code:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('https://httpbin.org/get', params=payload)
The payload here is a variable which defines the parameters of a request.

Related

I can't figure out how to put together an API with a key in the get request

I'm really new to programming, but I'm trying to put together my first API. It's going to a Fortnite tracker, and their documentation is nonexistent. It wants me to put in an API key in the header, but how am I supposed to put a header in the get request? Here's what I'm calling:
fnStats = requests.get('https://api.fortnitetracker.com/v1/profile/{platform}/{account}', headers = {'key': myPersonalKey'})
Here's what it returns, with my account name and platform plugged in correctly:
{"message":"No API key found in request"}
Is there an implied way to send the API key?
EDIT: Here is their 'documentation' page: https://fortnitetracker.com/site-api
I think first you need to create a API key suing your credentials through their website. Then pass on that key in GET request.
In header your "key" should be the keyname "value" should be actual value.
headers = {
'key_name': 'value'
}
Inside the .get() call, {'key': 'myPersonalKey'} is a placeholder. You need to replace the 'myPersonalKey' string with your own actual personal API key, which is something the doc tells you you have to get:
"To make use of our APIs we require you to use an API Key. To use the API key you need to pass it along as a header with your requests. Manage or Create API Keys"

How to delete or modify an element from a retrieved JSON API call?

As a Python newbie, I seem to struggle with a use case that I need to implement. The use case is that I need to retrieve some data using a REST call and later on send that data (modified) to another REST API but then with some fields manipulated, for example, rename a property or delete a property.
# get the data
service1 = requests.get(http://myrestservice_1.com)
# modify the data?
# delete or rename a property?
# send the data
service2 = request.post(url=http://myrestservice_2.com, json=service1.json())
Example of the data that I retrieve using a Rest call:
{
"prop1" : "value1",
"prop2" : "value2"
{
How can I, for example, delete or rename the prop2 value from the JSON when it needs to be forwarded the data to another service?
Thanks in advance!
requests.get() returns a Response object, which among other things contains the payload you want to decode. You can either do that yourself:
data = json.loads(service1.text)
or let requests do it for you.
data = service1.json()
Once you have modified data as necessary, you need to re-encode the data structure. Again, you can do so manually
service2 = request.post(url=http://myrestservice_2.com, data=json.dumps(data))
or let requests do it for you.
service2 = request.post(url=http://myrestservice_2.com, json=data)
response = requests.get()
gets you a Response object.
From there,
response.text
gets you a string with the response of the REST api.
response.status_code
gets you the HTTP status code of the call you just did.
And,
response.json()
gets you a Python dict that you can interact with.

python requests get request debugging

/api/stats
?fields=["clkCnt","impCnt"]
&ids=nkw0001,nkw0002,nkw0003,nkw0004
&timeRange={"since":"2019-05-25","until":"2019-06-17"}
I'm currently working on a API called naver_searchad_api
link to github of the api If you want to check it out. but i don't think you need to
the final url should be a baseurl + /api/stats
and on fields and ids and timeRange, the url should be like that
the requests I wrote is like below
r = requests.get(BASE_URL + uri, params={'ids': ['nkw0001','nkw0002','nkw0003','nkw0004'], 'timeRange': {"since": "2019-05-25", "until": "2019-06-17"}}, headers=get_header(method,uri,API_KEY,SECRET_KEY,CUSTOMER_ID))
final_result = r.json()
print(final_result)
as I did below instead
print(r.url)
it returns as below
https://api.naver.com/stats?ids=nkw0001&ids=nkw0002&ids=nkw0002&ids=nkw0002&fields=clkCnt&fields=impCnt&timeRange=since&timeRange=until
the 'ids' is repeated and doesn't have dates that I put.
how would I make my code to fit with the right url?
Query strings are key-value pairs. All keys and all values are strings. Anything that is not trivially convertible to string depends on convention. In other words, there is no standard for these things, so it depends on the expectations of the API.
For example, the API could define that lists of values are to be given as comma-separated strings, or it could say that anything complex should be JSON-encoded.
In fact, that's exactly what the API documentation says:
fields string
Fields to be retrieved (JSON format string).
For example, ["impCnt","clkCnt","salesAmt","crto"]
The same goes for timeRange. The other values can be left alone. Therefore we JSON-encode those two values only.
We can do that inline with a dict comprehension.
import json
import requests
params = {
'fields': ["clkCnt", "impCnt"],
'ids': 'nkw0001,nkw0002,nkw0003,nkw0004',
'timeRange': {"since":"2019-05-25","until":"2019-06-17"},
}
resp = requests.get('https://api.naver.com/api/stats', {
key: json.dumps(value) if key in ['fields', 'timeRange'] else value for key, value in params.items()
})
On top of complying with the API's expectations, all keys and values that go into the query string need to be URL-encoded. Luckily the requests module takes care of that part, so all we need to do is pass a dict to requests.get.

Python Requests: What fields append to the url

So I am using python Requests( http://docs.python-requests.org/en/latest/) to work with a REST api. My question is when using Requests what data field actually appends info to the url for GET requests? I wasn't sure if if I could use "payload" or if "params" does it.
It's all in the docs:
http://docs.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls
As an example, if you wanted to pass key1=value1 and key2=value2 to
httpbin.org/get, you would use the following code:
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
After all - you can of course easily test it, in case you're simply not sure which of two choices is the proper one.
As the example shows, http://httpbin.org (a site by the requests author) is a nice way to test any web programming you're doing.

how to output an HTML GET variable in python

there's lots of information on retrieving GET variables from a python script. Unfortunately I can't figure out how to send GET variables from a python script to an HTML page. So I'm just wondering if there's a simple way to do this.
I'm using Google App Engine webapp to develop my site. Thanks for your support!
Just append the get parameters to the url: request.html?param1=value1&param2=value2.
Now you could just create your string with some python variables which would hold the param names and values.
Edit: better use python's url lib:
import urllib
params = urllib.urlencode({'param1': 'value1', 'param2': 'value2', 'value3': 'param3'})
url = "example.com?%s" % params

Categories

Resources