How to Send Array String in Zeep - python-3.x

I have this below soap envelope where I have send string array.
<apiKey xsi:type="xsd:string">Ab12-Ab12-Ab12-Ab12</apiKey>ยง
<baseScheduleRollout xsi:type="flex:baseScheduleRollout" xmlns:flex="http://app.quinyx.com/soap/FlexForce">
<badgeNos xsi:type="flex:ArrayOfString" soapenc:arrayType="xsd:string[]">
<item1>1022</item1>
<item2>1030</item2>
<item2>10112330</item2>
</badgeNos>
<fromDateTime xsi:type="xsd:dateTime">2020-11-05T00:00:00</fromDateTime>
<toDateTime xsi:type="xsd:dateTime">2020-11-24T00:00:00</toDateTime>
I know how to send a soap request and my complextype is okay. But I think my string array passing system is wrong. Though I tried to use anyObject but still not working
from zeep import Client
from zeep import xsd
import datetime
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep.transports import Transport
wsdl = "https://api.quinyx.com/FlexForceWebServices.php?wsdl"
session = Session()
session.auth = HTTPBasicAuth('username', 'password')
client = Client(wsdl, transport=Transport(session=session))
ArrayOfString = client.get_element('ns0:ArrayOfObject')
badgeNo = ArrayOfString(['146223'])
data = { "apiKey" : "apikey" ,
"baseScheduleRollout" :{
"badgeNos":badgeNo,
"fromDateTime":xsd.SkipValue,
"toDateTime":xsd.SkipValue
}
}
result = client.service.wsdlGetBaseScheduleRolledoutHours(**data)
result
Error
LookupError: No element 'ArrayOfObject' in namespace https://api.quinyx.com/soap/FlexForce. Available elements are: -

Related

How deserialize protocol buffers from http response use python

I want to deserialize an API response to a python object whose content-type is protobuf, I use the ParseFromString method to parse the HTTP response, but only get a number 23, print the response content directly is b'\n\x08Hi,py-pb'. So, how do I deserialize the HTTP response to the python object?
proto file content:
syntax = "proto3";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
python code:
# _*_ coding: utf8 _*_
from google.protobuf.json_format import ParseDict, MessageToJson
from protos.greet_pb2 import HelloRequest, HelloReply
import httpx
import asyncio
async def send_req():
req = {'name': 'py-pb'}
msg = ParseDict(req, HelloRequest())
print(msg)
print(type(msg))
print(msg.SerializeToString())
async with httpx.AsyncClient() as client:
resp = await client.post('http://localhost:5044/greet/Greeter/SayHello', data=msg.SerializeToString(),
headers={'Accept': 'application/protobuf', 'Content-Type': 'application/protobuf'})
print('=========response=========')
# print(resp.stream)
# print(resp.content)
# print(resp.text)
resp_msg = HelloReply().ParseFromString(resp.content)
# resp_msg = HelloReply().SerializeToString(resp.content)
print(resp_msg)
asyncio.run(send_req())
Versions:
Python - 3.10.5
google.protobuf - 4.21.2
Related answer:
ParseFromString is a method -- it does not return anything, but rather fills in self with the parsed content.
Reference:
Google Protocol Buffers (protobuf) in Python3 - trouble with ParseFromString (encoding?)
ParseFromString is an instance method. So you want, e.g.:
hello_reply = HelloReply()
hello_reply.ParseFromString(resp.content)
The docs include an example using ParseFromString.
Here's a repro:
from google.protobuf.json_format import ParseDict, MessageToJson
from greet_pb2 import HelloRequest, HelloReply
rqst = {'name': 'py-pb'}
msg = ParseDict(rqst, HelloRequest())
tx = msg.SerializeToString()
print(tx)
print(tx.hex())
resp = HelloReply()
resp.ParseFromString(tx)
print(resp)
Yields:
b'\n\x05py-pb'
0a0570792d7062
message: "py-pb"
You can take the binary as hex and plug it into protogen to decode it.
Field #1: 0A String Length = 5, Hex = 05, UTF8 = "py-pb"

Python Zeep : 401 Untheorized

I am trying to run the below document using zeep in python.
Document
Name: wsdlGetSkillCategories
Binding: FlexForceBinding
Endpoint: https://api.quinyx.com/FlexForceWebServices.php
SoapAction: uri:FlexForce/wsdlGetSkillCategories
Style: rpc
Input:
use: encoded
namespace: uri:FlexForce
encodingStyle: http://schemas.xmlsoap.org/soap/encoding/
message: wsdlGetSkillCategoriesRequest
parts:
apiKey: xsd:string
Output:
use: encoded
namespace: uri:FlexForce
encodingStyle: http://schemas.xmlsoap.org/soap/encoding/
message: wsdlGetSkillCategoriesResponse
parts:
return: tns:SkillCategories
Namespace: uri:FlexForce
Transport: http://schemas.xmlsoap.org/soap/http
Documentation:
My Attempt:
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep.transports import Transport
wsdl = "https://api.quinyx.com/FlexForceWebServices.php?wsdl"
username = "username"
password = "pass"
session = Session()
session.auth = HTTPBasicAuth(username, password)
client = Client(wsdl, transport=Transport(session=session))
data = {"apiKey": "0000-0000-0000-0000"}
result = client.service.wsdlGetSkillCategories(**data);
text1 = (result.text)
print(text1)
Error:
Fault: 401 Unauthorized
Does anybody have any idea why I am getting this error?

Invalid or incomplete introspection result

When I am trying to run the below subscription code I am getting the error:
TypeError: Invalid or incomplete introspection result. Ensure that you are > passing the 'data' attribute of an introspection response and no 'errors' > were returned alongside: None.
What can I do to correct this?
from operator import concat
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport
from graphql import get_introspection_query
import pandas as pd
from gql.transport.websockets import WebsocketsTransport
# Select your transport with a defined url endpoint
count =0
transport = WebsocketsTransport(url='wss://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2')
# Create a GraphQL client using the defined transport
client = Client(
transport=transport,
fetch_schema_from_transport=True
)
# Provide a GraphQL query
lastID=""
query = gql(
"""
subscription swaps{
swaps(orderBy: timestamp, orderDirection: desc) {
id
timestamp
amount0In
amount1In
amount0Out
amount1Out
pair {
token0 {
id
symbol
}
token1 {
id
symbol
}
}
}
}
"""
)
for result in client.subscribe(query):
print (result)

Missing element SESSION_ID (LoginRequest.REQUEST_HEADER) on Python Zeep

I want to integrate an invoice api on python with zeep library. When I create Client object and send request with client.service.Login, Python is giving error Missing element SESSION_ID (LoginRequest.REQUEST_HEADER). I think the invoice api needs REQUEST_HEADER parameter with SESSION_ID in it. But how can i make it successfully. Any help will be appreciated.
import zeep
import requests
wsdl = 'URL'
client = zeep.Client(wsdl=wsdl)
client.service.Login('username','password')
ValidationError: Missing element SESSION_ID (LoginRequest.REQUEST_HEADER)
Okay I solved the problem. I only created dictionary with session_id and then passed this dictionary as a parameter to the Login function:
import zeep
import requests
wsdl = 'URL'
client = zeep.Client(wsdl=wsdl)
data = {'SESSION_ID':'0'}
session_id = client.service.Login(data, 'username', 'password')
print(session_id)
Output:
'SESSION_ID': 'xxxx-xxxx-xxxx.....',
'ERROR_TYPE': None

groovy api in pin payments secret key location

im doing an api for pin payment in pin.net.au and i encounter some errors like what you see in the bottom
`#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder'`,` version='0.5.0-RC2' )
import groovyx.net.http.*
import groovyx.net.http.HttpResponseDecorator
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.*
import groovyx.net.http.HttpResponseException
import groovy.swing.SwingBuilder
import javax.swing.JFrame
import wslite.http.auth.*
class Customers {
Customers(){
def rst = new RESTClient( 'https://test-api.pin.net.au/1/')
rst.auth.basic 'mySecretKey',''
def res = rst.post( path: 'customers'){
type ContentType.XML
xml {
cards{
email('pk_qTj9Umqmlf3o7lfa6F9nWw')
card[expiry_month]('12')
card[expiry_year]('2015')
card[cvc]('123')
card[name]('patrick pl')
card[address_line1]('23 frfds')
card[address_city]('Angeles')
card[address_postcode]('2009')
card[address_state]('ph')
card[address_country]('Philippines')
}
}
}
}
public static void main(String []args){
new Customers()
}
}
when i run the code the error was
May 12, 2014 1:07:35 PM org.apache.http.impl.client.DefaultRequestDirector handleResponse
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Caught: groovyx.net.http.HttpResponseException: Authorization Required
groovyx.net.http.HttpResponseException: Authorization Required
at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:240)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:475)
at groovyx.net.http.HTTPBuilder.post(HTTPBuilder.java:335)
at groovyx.net.http.HTTPBuilder$post.call(Unknown Source)
at PinPayment.Customers.<init>(Customers.groovy:16)
at PinPayment.Customers.main(Customers.groovy:39)
how could i make the authentication work for the code to be runable??
here is the link for the docs pin.net.au
Document indicates it requires basic HTTP authn.
Calls to the Pin Payments API must be authenticated using HTTP basic
authentication, with your API key as the username, and a blank string
as the password.
Therefore:
def rst = new RESTClient( 'https://test-api.pin.net.au/1/' )
rst.auth.basic 'secretAPIKeyHereAsString', ''
i found the right code for that particular api here def http = new RESTClient('https://test-api.pin.net.au/1/') http.headers['Authorization'] = 'Basic '+"tWqZl0MHsg5nUQdB6czrDQ:".getBytes('iso-8859-1').encodeBase64()

Resources