I create this function to update details of user, before this function I have to login and get the token that I have to use in the next call.
I use this for init:
# Select your transport with a defined url endpoint
transport = AIOHTTPTransport(url=HOSTNAME_GRAPHQL, headers={'Authorization': 'token'})
# Create a GraphQL client using the defined transport
client = Client(transport=transport, fetch_schema_from_transport=True)
and this funcion for call the mutation
def mutation_updateUser(client, id, username, firstName, lastName, access_token):
# headers = {
# #"X-Shopify-Storefront-Access-Token": access_token
# "Authorization": "Bearer " + access_token
# }
headers={'Authorization': f'Bearer ' + access_token}
query = gql(
"""
mutation updateUser($input: UpdateUserInput!) {
updateUser(input: $input) {
id
email
username
lastName
firstName
role
avatar
}
}
"""
)
params = {
"input": {
"id": id,
"username": username,
"firstName": firstName,
"lastName": lastName
}
}
request = client.execute(query, variable_values=params, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))
#return result
when I run the program I got this error:
**
Si è verificata un'eccezione: TypeError
execute() got an unexpected keyword argument 'headers'
File "D:\Python project\API ReadyTGo\mutation_updateUser.py", line 36, in mutation_updateUser
request = client.execute(query, variable_values=params, headers=headers)
**
SOLVED THE PROBLEM!!
I modify the function like this:
from gql.transport.aiohttp import AIOHTTPTransport
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
from questions import HOSTNAME_GRAPHQL
def mutation_updateUser(id, username, firstName, lastName, access_token):
# headers = {
# #"X-Shopify-Storefront-Access-Token": access_token
# "Authorization": "Bearer " + access_token
# }
#headers={'Authorization': f'Bearer ' + access_token}
headers = {"Authorization": f"Bearer {access_token}"}
_transport = RequestsHTTPTransport(url=HOSTNAME_GRAPHQL, use_json=True, headers=headers)
client = Client(transport=_transport, fetch_schema_from_transport=True)
query = gql(
"""
mutation updateUser($input: UpdateUserInput!) {
updateUser(input: $input) {
id
email
username
lastName
firstName
role
avatar
}
}
"""
)
params = {
"input": {
"id": id,
"username": username,
"firstName": firstName,
"lastName": lastName
}
}
request = client.execute(query, variable_values=params)
return request.json()
I hope to help someone
Related
I'm trying to unit test my code and make sure the my code returns a dict that matches the class. The error says the success field required (type=value_error.missing). If when I make the bool Optional it shows my actual results with success = None, message = None etc. So my actual class is returning empty and not equal to my wb_response.
class WorkBoardCreateUserResponse(BaseModel):
success: bool
message: Optional[str]
data: Optional[CreateUserData]
error: Optional[str]
error_description: Optional[str]
#mock.patch("workboard.requests.post")
#mock.patch("workboard.requests.get")
def test_create_workboard_user(self, mock_get, mock_post):
wb_response = {
"success":True,
"message": "",
"data": {
"totalCount": 1,
"user":
{ "user_id": 1,
"user_name":"",
"wb_email":"wb#email",
"email": "abc#company",
"first_name": "F name",
"last_name": "L name",
"manager_id": "manager#company",
"profile": {
"title": "emp",
"company": "company"
}
}
}
}
wb_user = WorkBoardUserRequest(
email= "abc#capone",
first_name= "F name",
last_name= "L name",
manager_id= "manager#company",
profile=WorkBoardProfile(
title="title",
company="company"
)
)
workboard_resp = json.dumps(wb_response)
mock_post.return_value.text = token_resp
mock_post.status_code = 200
mock_get.json.return_value.text = workboard_resp
final_response = json.loads(workboard_resp)
print(type(final_response))
employee = WorkBoard("client", "secret", "env", "vendor_token")
response = employee.create_workboard_user(wb_user)
self.assertEqual(response, WorkBoardCreateUserResponse(**final_response))
def create_workboard_user(self, wbUser: WorkBoardUserRequest) -> WorkBoardResponse:
"""
Grant access to the user by invoking the Third Party API
"""
wb_url = (PROD_URL if self.environment ==
"PROD" else NON_PROD_URL) + CREATE_USER_ENDPOINT
# Invoke the WorkBoard API to create user access
try:
create_user_response = requests.post(
wb_url, data=wbUser.json(), verify=True, allow_redirects=False, headers=self.headers
)
response = json.loads(create_user_response.text)
create_user_response = WorkBoardCreateUserResponse(**response)
logger.info(f"WorkBoard create user response : (%s)", create_user_response)
except ValidationError as validation_error:
print(f"Error while reading response : ", str(validation_error))
raise RuntimeError(str(validation_error))
except Exception as err:
logger.exception(f"Error while creating workboard user : %s", str(err))
raise RuntimeError(str(err))
return create_user_response
Hi I'm trying to convert a python code to C#. My Problem is, that I have a problem to make a HttpWebRequest. I don't get the cookies for the POST Request.
The Website response is 404. That is correct. But I think, I need the cookies for the POST request.
Is it correctly transleted? I have not done a HttpWebRequest yet.
C# Code:
public string email = "test#example.com"
public string password = "123456"
public string client_id = "111111111111"
public string login_url = "https://account.komoot.com/v1/signin"
var headers = new Dictionary<string, string> {
{"Content-Type", "application/json"}};
var payload = new Dictionary<string, string> {
{"email", email},
{"password", password},
{"reason", "null"}};
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = new CookieContainer();
var response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
var exeptionResponse = ex.Response;
var cookies = exeptionResponse ["Cookies"];
throw new WebException();
}
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(payload);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
catch (Exception exe)
{
throw new Exception();
}
Python Code:
import requests
import json
email = "test#example.com"
password = "123456"
client_id = "111111111111"
login_url = "https://account.komoot.com/v1/signin"
tour_url = f"https://www.komoot.de/user/{client_id}/tours"
s = requests.Session()
res = requests.get(login_url)
cookies = res.cookies.get_dict()
headers = {
"Content-Type": "application/json"
}
payload = json.dumps({
"email": email,
"password": password,
"reason": "null"
})
s.post(login_url,
headers=headers,
data=payload,
cookies=cookies,
)
url = "https://account.komoot.com/actions/transfer?type=signin"
s.get(url)
headers = {"onlyprops": "true"}
response = s.get(tour_url, headers=headers)
if response.status_code != 200:
print("Something went wrong...")
exit(1)
data = response.json()
tours = data["user"]["_embedded"]["tours"]["_embedded"]["items"]
for idx in range(len(tours)):
print(f"({idx+1}) {tours[idx]['name']}")
tour_nr = int(input("Tour ID: "))
tour_nr -= 1
tour_url = tours[tour_nr]["_links"]["coordinates"]["href"]
response = s.get(tour_url, headers=headers)
tour_data = json.loads(response.text)
tour = tours[tour_nr]
tour['coordinates'] = tour_data
print("Title:", T.name())
print(f"Duration: {T.duration()}s")
Tanks for your help!
Try it
public async Task<string> HttpClientAsync(string json, string token)
{
try
{
var JsonData = new StringContent(json, Encoding.UTF8, "application/json");
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
using (var client = new HttpClient(handler))
{
// System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var result = await client.PostAsync(url, JsonData);
string resultContent = await result.Content.ReadAsStringAsync();
return resultContent;
}
}
catch (Exception e)
{
return e.Message;
}
}
import requests
import json
import jwt
import datetime
APİ_KEY = "100 percent correct api key"
APİ_SECRET = "100 percent correct api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
print(token)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"headers": {
"authorization":"Bearer "+token,
"content-type":"application/json"
},
"body": {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
}
zoom_r = requests.post(endpoint, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)
I wanted to do a simple experiment with python like this, but I get an "invalid acces token" error, what could be the reason?
I thought a little more about my problem and solved the problem by changing the code as follows:
import requests
import json
import jwt
import datetime
APİ_KEY = "my api key"
APİ_SECRET = "my api secret"
payload = {
'iss':APİ_KEY,
'exp':datetime.datetime.now() + datetime.timedelta(hours=2)
}
token = jwt.encode(payload, APİ_SECRET)
endpoint = "https://api.zoom.us/v2/users/my_e-mail_is_written_here/meetings"
myData = {
"topic":"denemex",
"type":2,
"start_time":"2021-05-05T13:20",
"duration":"40",
"password":"1234"
}
headers = {"Content-Type":"application/json", "Authorization":"Bearer "+ token}
zoom_r = requests.post(endpoint, headers=headers, data=json.dumps(myData))
print(zoom_r.status_code)
print(zoom_r.text)
I am trying to get access to the Kerio Connect (mailserver) api which uses jsonrpc as a standard for their api.
There is Session.login method that works just fine, I get back a SESSION_CONNECT_WEBADMIN cookie that gets saved in the session:
SESSION_CONNECT_WEBADMIN=2332a56d0203f27972ebbe74c09a7f41262e5b224bc6a05e53e62e5872e9b698; \
path=/admin/; domain=<server>; Secure; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;
But when I then do my next request with the same session, I get back a message that tells me, that my session has expired:
{
"jsonrpc": "2.0",
"id": 2,
"error": {
"code": -32001,
"message": "Session expired.",
"data": {
"messageParameters": {
"positionalParameters": [],
"plurality": 1
}
}
}
}
So here's the Python script leading to that message
import json
import requests
userName = "username"
password = "password"
n=1
application = {}
application["name"] = "Log in"
application["vendor"] = "My Company"
application["version"] = "1.0"
params = {}
params["userName"] = userName
params["password"] = password
params["application"] = application
payload = {}
payload["jsonrpc"] = "2.0"
payload["id"] = n
n += 1
payload["method"] = "Session.login"
payload["params"] = params
headers = {}
headers["Content-Type"] = "application/json-rpc"
json_payload =json.dumps(payload, sort_keys=True, indent=2)
url = "https://<server>:4040/admin/api/jsonrpc/"
session = requests.Session()
response = session.post(url, headers=headers, data=json_payload, verify=False)
# Results in a token / a cookie with that token
payload2 = {}
payload2["jsonrpc"] = "2.0"
payload2["id"] = n
n += 1
payload2["method"] = "Users.get"
json_payload2 = json.dumps(payload2, sort_keys=True, indent=2)
response2 = session.post(url, data=json_payload2, verify=False)
print(response2.text)
What am I missing here because of my lack of experience?
[EDIT]:
I just now realise that when I log in with a browser, two cookies are actually created, each with another token, whereas I get only one cookie back when I try to access the api with Python. Why is that?
Cookies received with Chrome:
TOKEN_CONNECT_WEBADMIN
SESSION_CONNECT_WEBADMIN
Cookie received with Python:
SESSION_CONNECT_WEBADMIN
Working example:
import json
import urllib.request
import http.cookiejar
import ssl
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
urllib.request.install_opener(opener)
server = "https://mail.smkh.ru:4040"
username = "admin"
password = "pass"
ssl._create_default_https_context = ssl._create_unverified_context # disable ssl cert error
def callMethod(method, params, token=None):
"""
Remotely calls given method with given params.
:param: method string with fully qualified method name
:param: params dict with parameters of remotely called method
:param: token CSRF token is always required except login method. Use method "Session.login" to obtain this token.
"""
data = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
req = urllib.request.Request(url=server + '/admin/api/jsonrpc/')
req.add_header('Content-Type', 'application/json')
if token is not None:
req.add_header('X-Token', token)
httpResponse = opener.open(req, json.dumps(data).encode())
if httpResponse.status == 200:
body = httpResponse.read().decode()
return json.loads(body)
session = callMethod("Session.login", {"userName": username, "password": password, "application": {"vendor":"Kerio", "name":"Control Api Demo", "version":"8.4.0"}})
token = session["result"]["token"]
sessions = callMethod("Users.get",
{"query": {
"fields": [
"id",
"loginName",
"fullName",
"description",
"authType",
"itemSource",
"isEnabled",
"isPasswordReversible",
"emailAddresses",
"emailForwarding",
"userGroups",
"role",
"itemLimit",
"diskSizeLimit",
"consumedItems",
"consumedSize",
"hasDomainRestriction",
"outMessageLimit",
"effectiveRole",
"homeServer",
"migration",
"lastLoginInfo",
"accessPolicy"
],
"start": 0,
"limit": 200,
"orderBy": [
{
"columnName": "loginName",
"direction": "Asc"
}
]
},
"domainId": Example:"keriodb://domain/908c1118-94ef-49c0-a229-ca672b81d965"
},
token)
try:
user_names = []
for user in users["result"]["list"]:
print(user["fullName"], " (", user["loginName"], ")", sep="")
user_names.append(user["fullName"])
call_method("Session.logout", {}, token)
return users
except KeyError:
print('Error: {}'.format(users['error']['message']))
call_method("Session.logout", {}, token)
return None
I am using ODOO 11.0
how to return simple JSON object without JSON-RPC additional parameters
Here is my odoo controller code:
#http.route('/userappoint/webhook_test/',type='json', auth='public',method=['POST'], csrf=False,website=True)
def webhook_test(self,**kw):
response = {
'speech' : 'hello my name is shubham',
'displayText' : 'hello testing',
'source' : 'webhook'
}
return response
And I am getting this result :
{
"result": {
"displayText": "hello testing",
"source": "webhook",
"speech": "hello my name is shubham"
},
"id": "6eaced3e-6b0d-4518-9710-de91eaf16dd9",
"jsonrpc": "2.0"
}
But I need this :
{
"speech": "hello my name is shubham",
"displayText": "hello testing",
"source": "webhook"
}
Any help to point me in the right direction?
Thanks
Works on Odoo11. Just edit below portion of the function _json_response defined at odoo/odoo11/odoo/http.py near about line no : 621-630 as below & Restart the odoo service.
def _json_response(self, result=None, error=None):
response = {
'jsonrpc': '2.0',
'id': self.jsonrequest.get('id')
}
if error is not None:
response['error'] = error
if result is not None:
response['result'] = result
to new:
def _json_response(self, result=None, error=None):
response = {}
if error is not None:
response = error
if result is not None:
response = result
Then, restart the odoo service
Place the following code in any of your controller before you initialize the controller class
from odoo import http
from odoo.http import request, Response, JsonRequest
from odoo.tools import date_utils
class JsonRequestNew(JsonRequest):
def _json_response(self, result=None, error=None):
# response = {
# 'jsonrpc': '2.0',
# 'id': self.jsonrequest.get('id')
# }
# if error is not None:
# response['error'] = error
# if result is not None:
# response['result'] = result
responseData = super(JsonRequestNew, self)._json_response(result=result,error=error)
response = {}
if error is not None:
response = error
if result is not None:
response = result
mime = 'application/json'
body = json.dumps(response, default=date_utils.json_default)
return Response(
body, status=error and error.pop('http_status', 200) or 200,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)
class RootNew(http.Root):
def get_request(self, httprequest):
# deduce type of request
jsonResponse = super(RootNew, self).get_request(httprequest=httprequest)
if httprequest.mimetype in ("application/json", "application/json-rpc"):
return JsonRequestNew(httprequest)
else:
return jsonResponse
http.root = RootNew()
class MyController(http.Controller):