Adding string in <Class str> array in python3? - python

I have a string like this below
data = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
I am sending this data in a http request like
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers,data=data, auth=('user', 'pass'))
Now what i would like to do is e.g. i have a string in a variable like..
id=str('random string')
and i would like to add it in data like this..
data = '[{"cId": id, "name": "Test 02", "description": "My Test"}]'
But i am not able to add it. I have tried to first convert the entry in json and then adding it into the array. But server sends the exception back. How can i do that?

You could convert it to a list of dicts.Then convert it to str.(With json module):
import json
data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
tmp = json.loads(data_before)
tmp[0]["cId"] = str('random string')
data_after = json.dumps(tmp)
Then use data_after it like before:
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers, data=data_after, auth=('user', 'pass'))
Or pass it as json parameter directly in requests.post:
import json
data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
data_after = json.loads(data_before)
data_after[0]["cId"] = str('random string')
Then do:
import requests
headers = {
'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers, json=data_after, auth=('user', 'pass'))

data in request.post() should be a :
Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:Request.
If your data is json formatted, you can load the data and convert the string into a dict using json.load("<str in json format>").

Related

PythonAPI Request

Source=["SGD"]
Destination=["USD"]
Amount=[5000]
```import requests
url = "https://api.currencyfair.com/comparisonQuotes"
payload = "{\"currencyFrom\":\"SGD\",\"currencyTo\":\"EUR\",\"type\":\"SELL\",\"amountInfo\":
{\"amount\":50000,\"scale\":2}}"
headers = {
'user-agent': "vscode-restclient",
'content-type': "application/json",
'accept': "application/json"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
I need to pass values to payload string -
payload = "{"currencyFrom":"SGD","currencyTo":"EUR","type":"SELL","amountInfo":{"amount":50000,"scale":2}}"
Need to pass values to payload using 3 list created above```
Could you please try to explain a bit more what you're after?
I suspect what you mean is that you'd like to dynamically update the values in the text payload every time you call the function to post data.
I'd usually go about doing this by creating a placeholder string then updating that by replacing placeholder values at runtime.
payload = "{\"currencyFrom\":\"#currencyFrom\",\"currencyTo\":\"#currencyTo\",\"type\":\"SELL\",\"amountInfo\": {\"amount\":#amountInfo,\"scale\":2}}"
currencyFrom = 'USD'
currencyTo = 'EUR'
amountInfo = 50000
payload = payload.replace('#currencyFrom', currencyFrom).replace('#currencyTo', currencyTo).replace('#amountInfo', amountInfo)
Looking at the API you're trying to interact with, this is a sample of what it expects:
{"currencyFrom": "EUR",
"currencyTo": "GBP",
"type": "SELL",
"amountInfo": {"amount": 100},
"ignoreFee": false}
This is a JSON object that follows a specific format, if you try and pass a list as opposed to a string in the "currencyFrom", "currencyTo" fields etc you'll get an error.
To get multiple values as responses simply conduct multiple requests to the API, for example:
payload = "{\"currencyFrom\":\"#currencyFrom\",\"currencyTo\":\"#currencyTo\",\"type\":\"SELL\",\"amountInfo\": {\"amount\":#amountInfo,\"scale\":2}}"
currencyFrom = ['USD', 'GBP']
currencyTo = ['EUR', 'CHF']
amountInfo = 50000
payload = payload.replace('#currencyFrom', currencyFrom).replace('#currencyTo', currencyTo).replace('#amountInfo', amountInfo)
for currFrom in currencyFrom:
for currTo in currencyTo:
for amount in amountInfo:
payload = payload.replace('#currencyFrom', currFrom ).replace('#currencyTo', currTo ).replace('#amountInfo', amount )
response = requests.request("POST", url, data=payload, headers=headers)
Hope this makes sense!
Edit: Updating code as per your comments.

Python - print some data from response

I'm making a request:
import request in python:
url = "http://myweb.com/call"
payload = {}
headers = { 'Content-Type': 'application/json', 'Token': '123456789' }
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
and I'm receiving and printing the response as :
{"name":"Peter","LastName":JOHN,"RegDate":"2020-03-25T17:34:42.5306823Z","Number":7755}
but I want the print statement to show only "Name" and "Number" params. Not the whole response should be printed. How do I do this?
Thanks in advance.
Response is a dictionary object, so you want to print two values from that dictionary using the keys for those values:
response_text = response.text.encode('utf8')
print(response_text['name'], response_text['Number'])
edit: the dict is actually deeper within the response object than I originally understood.
You can do this:
import json
response = requests.request("POST", url, headers=headers, data = payload)
response_txt=json.loads(response.text.encode('utf8'))
print(response_txt['name'])
print(response_txt['Number'])
response.text.encode('utf8') produces a string, so you need import the json library and convert that string to an object with json.loads. Then you can access the keys with response_txt['name'] and response_txt['Number'].

How to use python api get request

I use the below function to get data from the web , but failed. I wonder whether urllib.quote use incorrect
i have used urllib.urlencode(xx) but it show not a valid non-string sequence or mapping object
and my request data is:
[{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}]
Anyone can help. Thanks a lot !!!
###This Funcation call API Post Data
def CallApi(apilink, indata):
token = gettoken()
data = json.dumps(indata, ensure_ascii=False)
print(data)
headers = {'content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer %s' % (token)}
proxy = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
DataForGet=urllib.quote(data)
NewUrl= apilink + "?" + DataForGet
request = urllib2.Request(NewUrl, headers=headers)
response = urllib2.urlopen(request, timeout=300)
message = response.read()
print(message)
Error:
the err message below: File "/opt/freeware/lib/python2.7/urllib2.py", line 1198, in do_open raise URLError(err)
You could see the comment of urlencode
Encode a dict or sequence of two-element tuples into a URL query string
So you could choose removing the outer []
{"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}
Or use a two-element tuple
(('Keys', 'SV_cY1tKhYiocNluHb'), ('Details', [{...}]...)
Demo
>>> import urllib
>>> s = {"Keys": "SV_cY1tKhYiocNluHb", "Details": [{"id2": "PK_2gl9xtYKX7TJi29"}], "language": "EN", "id": "535985"}
>>> urllib.urlencode(s)
'Keys=SV_cY1tKhYiocNluHb&Details=%5B%7B%27id2%27%3A+%27PK_2gl9xtYKX7TJi29%27%7D%5D&language=EN&id=535985'
>>>

How to create a list from api reponse and remove duplicates

I want to make a list from api json response as shown for each ticket in jira and remove any duplicates
I can get the values for each ticket but not able to make it as list and remove duplicates from it to process
Here is the api json response for each ticket
response = {
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "1831845",
"self": "https://jira.com/login/rest/api/latest/issue/1845",
"key": "pc-1002",
"fields": {
"customfield_1925": {
"self": "https://jira.com/login/rest/api/2/customFieldOption/1056",
"value": "windows",
"id": "101056"
}
so i have script like this:
import requests, json
tick = """jira: pc-1002,pc-1003,pc-1005
env"""
ticks = tick.replace(' ','').split(':')[1].split('\n')[0].split(',')
print(ticks)
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
print(resp)
so it prints all the values like below :
output:
windows1
windows2
windows1
I want the output values to be unique and as it may end up having duplicates.
I wanted output as below
['windows1', 'windows2']
Simply add each response to a list of responses, and use Python's convenient "in" operator to check if each response is already in the list. Something along the lines of:
allResponses = []
for i in ticks:
url = "https://jira.com/login/rest/api/latest/issue/" + str(i)
print(url)
response = requests.request("GET", url, verify=False)
response = json.loads(response.text)
resp = response['fields']['customfield_1925']['value']
if resp not in allResponses:
print(resp)
allResponses.append(resp)

Unexpected token END OF FILE at position 0 on Python POST request to Firebase

I am trying to send a message via Firebase to a certain client. This is my current (test) code:
import json
import requests
import urllib
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Content-Type': 'application/json', 'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
payload = json.dumps(payload)
res = requests.post(server, headers=headers, json=payload)
return res
which produces the following error, returned by Firebase:
JSON_PARSING_ERROR: Unexpected token END OF FILE at position 0.
The following JSON sent to Firebase seems correct to me:
{
"data": {
"type":"dataUpdate"
},
"to":"xxx"
}
which is in the format described by the Firebase documentation. Any idea why Firebase doesn't accept the given data?
When you use json=payload as a parameter to requests.post() you don't need to specify 'Content-Type': 'application/json' in the header. In addition, you are passing a string when the parameter should be payload as a dict (ie. no need for json.dumps())
Try this:
def send_message():
server = "https://fcm.googleapis.com/fcm/send"
api_key = "xxx"
user_token = "xxx"
headers = {'Authorization': 'key=' + api_key}
data = {"type": "dataUpdate"}
payload = {"data": data, "to": user_token}
res = requests.post(server, headers=headers, json=payload)
return res

Categories