import requests
import json
url = "********"
payload = json.dumps({
"username": "*****",
"password": "*****"
})
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
#*** Convert response into a dictionary ***
r = json.loads(response.text)
# *** print the value of they key 'accessToken'
bearerToken = r['accessToken']
print(bearerToken)
Output
{'accessToken': 'e************************************', 'tokenType': 'Bearer'}
What am I trying to achieve?
Grab only the censored code after 'accessToken' and store the new Access Token in a string to use it in HTTP requests.
Note: 'accessToken' is a value of another key called accessToken. So the traditional method of printing the value of the key has already been used in the output shown above.
Complete output:
{
"accessToken" : {
"accessToken" : "e******************",
"tokenType" : "Bearer"
},
"refreshToken" : {
"id" : "6*************",
"lastAccessedTime" : 1***********,
"refreshToken" : "e*************"
}
}
In Python, you can use substrings to accomplish what you want. If the length of the prefix is constant, then all you would need to do is use a slice with constant index,
In your example, it looks like you have an accessToken key, and inside that key is another dictionary holding a key that can change between entries. Assuming that you want the censored portion after e in accessToken, you can access that using:
bearerToken = r['accessToken'][accessToken][1:]
This will give you the access token "******************", which is everything from index 1 onwards. If you just want the entire string, you can omit the [1:] portion.
The solution was to edit the code provided by yeeshue99, the 2nd value to 'accessToken' with the '' marks. the [1:] was also not needed.
Solution
bearerToken = r['accessToken']['accessToken']
Related
Hi I'm using Groovy HTTPBuilder to make a GET call with request body similar like this:
def obj = [:]
// add the data in map - obj
def http = OkHttpBuilder.configure {
request.uri = "URL"
request.uri.path = "/path"
request.headers.put("Authorization", "token value")
request.cookie("fingerprint", "fingerprint value")
request.accept ="application/json"
request.headers.put("Content-Type", "application/json;")
def jsonBody = JsonOutput.toJson(obj)
request.body = jsonBody
response.failure { FromServer fromServer, Object body ->
assertHttpFailure(fromServer, body)
}
}
http.get()
But, getting an groovy.json.JsonException with below details
Unable to determine the current character, it is not a string, number, array, or object
The current character read is 'R' with an int value of 82
Unable to determine the current character, it is not a string, number, array, or object
line number 1
index number 0
Required request body is missing: public org.springframework.http.ResponseEntity<java.util.List
Any suggestions ? why request body says missing
So I have an endpoint that I am trying to integrate in Python which accepts a POST request and according to the API documentation, the payload is to be formatted this way:
payload = "{\r\n\"serviceCode\" : \"V-TV\",\r\n\"type\" : \"DSTV\",\r\n\"smartCardNo\" : \"10441003943\"\r\n}\r\n\r\n\r\n\r\n\r\n"
I want the values of type and smartCardNo to be dynamic, i.e I am going to get the values from a form in the frontend and pass it to the backend but I am finding it difficult to do so.
If I format the payload this way(which of course allows ease of passing variable):
{
"serviceCode": "V-TV",
"type": "DSTV",
"smartCardNo" : "10441003943"
}
I get this error:
{'required_fields': ['The service code field is required.'], 'message': 'Service Code is not supplied', 'status': '301'}
Could anyone tell me how I can pass the values for type and smartCardNo dynamically in the fist format(the format specified in the documentation)....any help will be greatly appreciated.
you can simply use the .format()
dict_values = {
"serviceCode": "V-TV",
"type": "DSTV",
"smartCardNo" : "10441003943"
}
payload = """{{"serviceCode":"{serviceCode}","type":"{mytype}","smartCardNo":"{smartCardNo}"}}""".format(
serviceCode = dict_values["serviceCode"],
mytype = dict_values["type"],
smartCardNo = dict_values["smartCardNo"]
)
output:
'{"serviceCode":"V-TV","type":"DSTV","smartCardNo":"10441003943"}'
If you really need the same format as in your payload example, simple use:
payload = "{{\r\n\"serviceCode\" : \"{serviceCode}\",\r\n\"type\" : \"{mytype}\",\r\n\"smartCardNo\" : \"{smartCardNo}\"\r\n}}\r\n\r\n\r\n\r\n\r\n".format(
serviceCode = dict_values["serviceCode"],
mytype = dict_values["type"],
smartCardNo = dict_values["smartCardNo"]
)
and your output will be:
'{\r\n"serviceCode" : "V-TV",\r\n"type" : "DSTV",\r\n"smartCardNo" : "10441003943"\r\n}\r\n\r\n\r\n\r\n\r\n'
I'm trying to get back a list of calendar events with Microsoft Graph API but having problems with passing date variable in the query parameters.
If I hardcode the uri value to:
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `'2018-12-10T19:30:34.654Z'`,
then the request works. But if I try to pass the date variable with toISOString, I get an error. I've tried with or without backticks, and calling toISOString in the uri value and in the nextMonday function. Still doesn't work. Anyone have any ideas? Thanks!
function nextMonday(date){
var monday = new Date(date);
monday.setDate(monday.getDate() + (1 + 7 - monday.getDay()) % 7);
return monday.toISOString();
}
let date = new Date();
let m = nextMonday(date);
const options = {
uri: 'https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge ' + `m`,
auth: {
bearer: token,
},
headers: {
'content-type': 'application/json'
},
json: true // Automatically parses the JSON string in the response
};
You need to (1) use ${m} to add the value and (2) wrap it in single quotes.
uri: https://graph.microsoft.com/beta/me/calendar/events?$filter=start/dateTime ge '${m}',
I'm currently working on fetching customer data from cdon, it's an e-commerce platform. They have their API documentation here:
CDON Api Docu
First let me show you my code:
myToken = '<token here>'
myUrl = 'https://admin.marketplace.cdon.com/api/reports/d8578ef8-723d-46cb-bb08-af8c9b5cca4c'
head = {'Authorization': 'token {}'.format(myToken),
'Status':'Online',
'format':'json'}
filters = '?filter={"Status":["Online"],"format": ["json"] }}'
response = requests.get(myUrl + filters, headers=head)
report = response.json()
print(report.products)
This is returning only the parameters. like for example at at this JSON: CDON Github
Status has a value Online this online is a group of itemsthat I only want to get.
What I'm trying to get is a response like this:
{
"Products": [
{
"SKU": "322352",
"Title": "Fabric Cover",
"GTIN": "532523626",
"ManufacturerArticleNumber": "",
"StatusCDON": "Online",
"ExposeStatusCDON": "Buyable",
"InStock": 0,
"InStockCDON": 0,
"CurrentPriceSE": null,
"OrdinaryPriceSE": null,
"CurrentPriceCDONSE": 299.0000,
"OrdinaryPriceCDONSE": null,
"CurrentPriceDK": null,
"OrdinaryPriceDK": null,
"CurrentPriceCDONDK": null,
"OrdinaryPriceCDONDK": null,
"CurrentPriceNO": null,
"OrdinaryPriceNO": null,
"CurrentPriceCDONNO": null,
"OrdinaryPriceCDONNO": null,
"CurrentPriceFI": null,
"OrdinaryPriceFI": null,
"CurrentPriceCDONFI": null,
"OrdinaryPriceCDONFI": null
},
Which means the full list of the items that are Online
How should I put this... among all the API's I tried this one is very confusing, is this even RestFul? If I can achieve the python equivalent of this C# sample code:
public string Post(Guid repordId, string path)
{
var filter = new JavaScriptSerializer().Serialize(new
{
States = new[] { "0" } // Pending state
});
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair("ReportId", repordId.ToString()),
new KeyValuePair("format", "json"),
new KeyValuePair("filter", filter)
});
var httpClient = new HttpClient() { BaseAddress = new Uri("https://admin.marketplace.cdon.com/") };
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("api", ApiKey);
var response = httpClient.PostAsync(path, content).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
I may be able to undestand how this API works, the response that I got was taken manually from their report function in JSON format.
Image
I made many attempts and at that code ( my code ) I stopped, being on this for 4 hours made me give up and ask. Trust that I have searched as many references as I could. It's really confusing.
How do I get the response that I want? Filtering via url? or via header? is this even restful? Help T_T
The documentation states in the first line, emphasis mine:
In order to generate a report you perform a POST call to the reports API with the parameters you wish to use for the report.
Your Python code does not make a POST request, you are trying a GET request. The documentation goes on
[...] to filter on Swedish orders you set the CountryCodes
attribute to “Sweden” and to get returned and cancelled orders you set
the States attribute to 2 and 3. So in the end the filter would look
like this:
{
"CountryCodes": [ "Sweden" ],
"States": ["2", "3"]
}
So you need to prepare a filter object (a dictionary in Python) with the filters you want. Luckily the Python syntax for dictionaries is equivalent (Python is flexible and also allows single-quoted strings):
filter = {
'CountryCodes': [ 'Sweden' ],
'States': [ '0' ]
}
The documentation goes on
You then post the parameters as form data (content-type:
application/x-www-form-urlencoded) so the request body would look like
this:
ReportId=d4ea173d-bfbc-48f5-b121-60f1a5d35a34&format=json&filter={"CountryCodes":["Sweden"],"States":["2","3"]}
application/x-www-form-urlencoded is the default for HTTP post, the requests module knows that and does this for you automatically. All you need to do is to prepare a data dict which will contain the data you want to post.
data = {
'ReportId': 'd4ea173d-bfbc-48f5-b121-60f1a5d35a34',
'format': 'json'
'filter': json.dumps(filter)
}
The filter parameter is supposed to be in JSON format. You must encode that yourself via json.dumps().
import json
head = { ... as above }
filter = { ... as above }
data = { ... as above }
response = requests.post(url, data, header=head)
I'll leave figuring out setting the Authorization header properly as an exercise for you. Partly because it isn't hard, partly because I have no intention of creating an API key with this website just for testing this and partly because it's entirely possible that your current header already works.
How can we capture only the email address in an api response for the gmail API. The
fields parameter is set to payload/headers, which returns way more data than we need in the response.
All we need is the value from one name/value pair in the JSON response; for example
The full response as we have it now looks something like this
{
"payload": {
"headers": [
{
"name": "Delivered-To",
"value": "xxxxxxx"
{
"name": "Received",
"value": "xxxxxxxx"
},
{
"name": "Received-SPF",
"value": "----"
},......
{
"name": "To",
"value": "xxxxxxx"
}, ...... E.T.C........E.T.C ......
/*All we want is one name/value pair to be returned e.g. */
{
"payload": {
"headers": [
{
"name": "X-Failed-Recipients",
"value": "............."
}
]
}
A better question might be is there a better way to capture bounced/returned mail than this via the gmail API?
Also, is it possible to request an XML response instead of JSON. How can that be done for the gmail API?
Thanks !!
You can do messages.get(format=METADATA, metadataIncludeHeaders=["To", "From", "Subject"]) for example, now to just request the specific headers you care about . Note this only works with the metadata format (it won't include the body also, if you want all the body you get the full email. Based on the list of headers, shouldn't be too hard to turn that into a map/dict of key => [list, of, values].
As to your second question, yes you can definitely request response in any format you want. That's a standard Google API question though. I can't find a good reference (surely some searching will) but typically you can set an "alt=xml" or "alt=" query parameter to get response in that format. Not sure how this is exposed in any particular client library.
First you need to get your message payload and then you want to use the getall method to return a list of headers and then you can use the getitem to pull any specific header you want from that list.
I converted the String into a String and took it as a JSON Array and iterated through it to take the JSON Object that I required.
private static DirtyMail getHeaderParts(DirtyMail mail, List<MessagePartHeader> headers)
{
try {
//Convert the header into JSON Array for easy processing of data.
JSONArray headerArray = new JSONArray(headers.toString());
for(int n = 0; n < headerArray.length() ; n++) {
JSONObject jsonObject = headerArray.getJSONObject(n);
//Pull date
if(jsonObject.get(Constants.DATE)!=null) {
mail.setDate(jsonObject.getString(Constants.DATE));
}
//Pull Subject
//Pull reply-to address
//Pull delivered-from address
//Pull delivered-to address
Log.d(TAG, "JSON Object : "+ jsonObject);
}
//Log.d(TAG,"header String: "+headers.toString());
} catch (Exception e) {
e.printStackTrace();
}
return mail;
}
I kept these values in the Constant class :
// Data pulled from inside the header
public static final String DATE = "Date";
public static final String SUBJECT = "Subject";
public static final String REPLY_TO = "Reply-To";
public static final String DELIVERED_TO = "Delivered-To";
public static final String FROM = "From";
I don't know if this is the best fix for this, but this works and gives the data as I require.