NVM request working in Postman but not in Python - python-requests

I am trying to execute a request in the New Voice Media API (request documentation) from python. When I execute this request in Postman, everything works perfectly, but from my script I get this error :
{'status': 400, 'title': 'One or more validation errors occurred', 'detail': 'The ScheduleId property is required.'}
Here is my Postman setup :
Here is my python request :
headers = {
'Accept': 'application/vnd.newvoicemedia.v4+json',
'Authorization': 'Bearer '+acces_token_users_write,
}
url = 'https://emea.api.newvoicemedia.com/useradmin/users/'+user_id+'/schedules'
body = {'agentSchedules': [{'scheduleId': schedule_id }]}
response = requests.put(url, headers=headers, data=body)
print(response.json())
Every other NVM API request seems to work perfectly from python. I've also tried writing the key 'scheduleId' with different caps combinations.
Do you have any idea what could cause this difference Postman / Python ?

Related

Microsoft Graph 'Unable to read JSON request payload' error when inviting users to Azure AD in Python with Requests

I'm trying to automate inviting users to an Azure AD using the MS Graph API but get an 'Unable to read JSON request payload' error.
I'm pulling data from a ticketing system, retrieving the current AAD users and diff-ing both. Then I'll be pushing the new ones into the AAD and updating them to include them in an Attendees AD Security group.
I created a Python Azure Function that calls the Graph API with Requests :
def insert_users(users_emails):
logging.info('Inserting new users in AAD')
token = generate_auth_token()
users_emails = users_emails[:2]
added_attendees = []
for email in users_emails:
req_body = {
"invitedUserEmailAddress" : email
, "inviteRedirectUrl" : "https://myapp.com"
}
body_length = sys.getsizeof(req_body)
req_headers = {
'Authorization' : 'Bearer {0}'.format(token)
, 'Content-Type' : 'application/json; charset=utf-8'
, 'Content-Length' : str(body_length)
}
response = requests.post(
'https://graph.microsoft.com/v1.0/invitations'
, headers = req_headers
, data = req_body
)
response = response.json()
logging.info(response)
added_attendees.append(email)
return added_attendees
The Graph API sends back the following error message :
{'error':
{'code': 'BadRequest',
'message': 'Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.',
'innerError':
{'request-id': '4ff5332d-d280-4b0d-9e04-a7359ab0e2fb', 'date': '2020-05-27T14:51:18'}
}
}
I tried adding the charset to the Content-Type header but it won't work. I read someplace the Content-Length could be useful so I added it too, to no avail.
Tests run ok in Postman and I'm already performing a POST request against the Azure AD API to get an Access Token so the Requests JSON body is parsed fine then. I also tried using single or double quotes in the JSON payload but it didn't work either.
My take is something is misinterpreted by the Graph API but I can't figure out what.
Thanks forward for your help !
i found a solution. Instead of passing a data argument to the request.post method, I passed a json= argument
response = requests.post(
'https://graph.microsoft.com/v1.0/invitations'
, json={'invitedUserEmailAddress':email,'inviteRedirectUrl':'https://myapp.com'}
, headers = req_headers
)

http request work in postman but not in browser

I am able to send post and get request from postman but when i actually send that request from browser it is not able to fetch records and in console shows error "body: {error: "Collection 'undefined' not found"}".
tried for both Get and Post requests they both provide the data in response in POSTMAN, but in browser it does not work.shows error "body: {error: "Collection 'undefined' not found"}".
in same project at different place i am also using in-memory-data-base, to which i am able to make /GETRequest and recieve the data in response.
homepage.ts:=============
public AllItem: AllItems[] ;
getAllItems(): void {
console.log('AA');
this.itemService.getAllItems() //(this.AllItems)
.subscribe(AllItem => this.AllItem = AllItem );
console.log(this.AllItem);
console.log('EE');
}
item.Service.ts:===============
private itemsUrl = 'api/items'; // URL to web api
private allItemsUrl = 'http://*************.azurewebsites.net/items';
getAllItems(): Observable<AllItems[]>{
console.log('CC');
return this.http.get<AllItems[]>(this.allItemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<AllItems[]>('getHeroes', []))
);
}
// this get request work properly and gives response data from in-memoery-db
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.itemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Item[]>('getHeroes', []))
);
}
in POSTMAN it gives data as
{
"items": [
{
"category": "Drink",
"item": "Coffee",
"price": "5$"
}]
}
in Browser console
core.js:15724 ERROR
body: {…}, url: "http://**********.azurewebsites.net/items", headers: HttpHeaders, status: 404, statusText: "Not Found"}
body: {error: "Collection 'undefined' not found"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 404
statusText: "Not Found"
url: "http://*************.azurewebsites.net/items"
__proto__: Object
Got the solution for this, Actually i was using in-memory-web-api at some other places in same project,
Not found collection error suggest that you have used angular-in-memory-web-api before. You need to remove everything related to that from your project, so that you are able to use external api and db.
"InMemoryWebApiModule.forRoot(InMemoryDataService)"
Angular in-memory-web-api, it replaces the HttpClient module's HttpBackend SO it needs to be removed first before using actual server and DB
After this i faced another issue that Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
For this we need to use following in our node server in Azure.
var cors = require('cors');
app.use(cors({origin: '*'}));

Sending headers to post request

I have this python code that does not work as expected.
import requests
import json
API_ENDPOINT = "https://lkokpdvhc4.execute-api.us-east-1.amazonaws.com/mycall"
data = {'mnumber':'9819838466'}
r = requests.post(url = API_ENDPOINT, data = json.dumps(data))
print (r.text)
This will return an error:
{"stackTrace": [["/var/task/index.py", 5, "handler", "return
mydic[code]"]], "errorType": "KeyError", "errorMessage": "''"}
When I test the API using Amazon console's gateway, I get the expected output (i.e. string like "mumbai"). It means this is client side issue. I have confirmed this by using "postman" as well that returns the same error as mentioned above. How do I send correct headers to post request?
You can create a dictionary with the headers such as
headers = {
"Authorization": "Bearer 12345",
"Content-Type": "application/json",
"key" : "value"
}
Then at the point of making the request pass it as a keyword argument to the request method i.e .post() or .get() or .put
This will be
response = requests.post(API_ENDPOINT, data=json.dumps(data), headers=headers)

Python Request Session JIRA REST post http 405

Using python requests session I can connect to JIRA and retrieve issue information ...
session = requests.Session()
headers = {"Authorization": "Basic %s" % bas64_val}
session.post(jira_rest_url, headers=headers)
jira = session.get(jira_srch_issue_url + select_fields)
# select_fields = the fields I want from the issue
Now I'm trying to post a payload via the JIRA API, using a fixed issue url e.g. "https://my_jira_server.com:1234/rest/api/latest/issue/KEY-9876"
Which should be a case of the following, given: https://developer.atlassian.com/jiradev/jira-apis/about-the-jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-edit-issues
payload = { "update": {
"fixVersions": [ {"set": "release-2.139.0"} ]
}}
posted = session.post(jira_task_url, data=payload)
# returns <Response [405]>
# jira_task_url = https://my_jira_server.com:1234/rest/api/latest/issue/KEY-9876
But this doesn't appear to work! Looking into the http 405 response, suggests that my payload is not properly formatted! Which notably, is the not easiest thing to diagnose.
What am I doing wrong here? Any help on this would be much appreciated.
Please note, I am not looking to use the python jira module, I am using requests.session to manage several sessions for different systems i.e. JIRA, TeamCity, etc..
Found the solution! I had two problems:
1) The actual syntax structure should have been:
fix_version = { "update": { "fixVersions": [ {"set" : [{ "name" : "release-2.139.0" }]}]
2) To ensure the payload is actually presented as JSON, use json.dumps() which takes an object and produces a string (see here) AND set 'content-type' to 'application/json':
payload = json.dumps(fix_version)
app_json = { 'content-type': 'application/json' }
session.put(https://.../rest/api/latest/issue/KEY-9876, headers=app_json, data=payload)
Rather than trying to define the JSON manually!

I see the response body in chrome developer tools, but unable to retrieve it inside Front End

I am currently working in a project where I need to send a response from grails back end to ReactJs front End. I was able to send the response from grails controller using "response" but unable to extract the response body on the ReactJs side. I tried checking in the following and found null value or undefined.
response.content, response.body
I see the response I sent back from grails in chrome web developer tools "Network" tab. but unable to find out which field of response object actually has it. Any help regarding this will be highly appreciated.
My http request.
post: function(url, item) {
return fetch(baseUrl + url, {
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain'
},
method: 'post',
body: item
}).then(function(response) {
alert(response);
return response ;
});
},
grails
response << "there is an error"
Try render 'there is an error'
Or if you need to render JSON:
render [someKey: 'there is an error'] as JSON
To understand how grails controllers and views work read this simple example.
Have you tried content-type: 'application/json'

Resources