How to post an object to sonicwall api with python? - python

recently my admin asked me if I can create an app to input some data into our Sonicwall.
I found some API, created an account, and ran some "get" methods, which worked just fine. I am trying now to post a new object into our pv4 rules and cannot get over it.
The problem is when I write something like this:
def postIpv4Object(session):
body = {
"address_objects": [{
"ipv4": {
"name": "Test 1",
"zone": "LAN",
"host": {
"ip": "192.168.168.10"
}
}
}
]
}
resp = session.post(fw + '/api/sonicos/address-objects/ipv4', headers=good_headers,params=body, verify=False)
I am still getting this error:
{'status': {'info': [{'code': 'E_INVALID_API_CALL',
'level': 'error',
'message': 'Expected a request body.'}],
'success': False}}
I am reading docs but cannot really figure this out. Does anyone tried it and help me out a little?

After a couple of days of trying, I figured that "body" should be converted into JSON type, and instead of "params I need to use "data".

Related

Jira API : when using PUT call getting "no single-String constructor/factory method"

I was trying to update a custom field on a Jira ticket using Jira API, following this Jira Documentation. however, I am getting the below error.
{'errorMessages': ['Can not instantiate value of type [simple type, class com.atlassian.jira.rest.v2.issue.IssueUpdateBean] from JSON String; no single-String constructor/factory method']}
this is my code:
data = {'update': {'customfield_25305': [{'set': [{'value': '1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9'}, {'value': 'c6f1e31ce0138cba658f769accaac729bebc42d6'}]}]}}
data = json.dumps(json.dumps(data)) #because the API accepts only strings enclosed in double quotes
upload = requests.put(url, headers=headers, data=data)
print(upload.json())
as per the documentation, I tried "/editmeta" the custom field I am trying to update is editable and has the following attributes.
{'required': False, 'schema': {'type': 'string', 'custom': 'com.atlassian.jira.plugin.system.customfieldtypes:textfield', 'customId': 25305}, 'name': 'Commit ID(s)', 'fieldId': 'customfield_25305', 'operations': ['set']}
Not sure what I am doing wrong here, any help would be appreciated!
Tried jira documentation
and searched through the Jira community none of the answers helped, everything points to malformed data but the data that I am passing is as per documentation.
the end result would be a 204 status code.
I think is a matter of single quotes.
As far as I remember, for valid JSON it should be double quotes.
{
"update": {
"customfield_25305": [{
"set": [{
"value": "1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9"
}, {
"value": "c6f1e31ce0138cba658f769accaac729bebc42d6"
}]
}]
}
}
I use to do a online validator tool to my JSON strings when I got stuck.
E.g. https://jsonlint.com/ (first result on google)
I was able to resolve the issue, the proper formatting for data is as below:
{"fields": {"customfield_25305": "\"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\", \"c6f1e31ce0138cba658f769accaac729bebc42d6\", \"1c1a07d49af1b1cde8a1a7bd93cbbeef8efd50c9\""}}

How to change error format of all errors using Connexion + Tornado

I'm using Connexion (https://github.com/zalando/connexion) to make sure my openapi-specification is well-followed and to have easy integration points to connect my routes to the underlying functions.
In any case, the default error responses from Connexion are json responses following the Problem Details for HTTP APIs RFC. That is the following format, e.g.:
{
"detail": "None is not of type 'object'",
"status": 404,
"title": "BadRequest",
"type": "about:blank"
}
However, I would like to change the format of all errors sent to something like:
{
error: {
code: 400,
message: 'BadRequest',
detail: 'ID unknown'
innererror: {...}
}
}
I can not find any way to intercept every error to change the format of what is returned. I know I can extend the connection.exception.ProblemException class and add a dict to the extparameter in its constructor, but for any 400 error for example, I can't intercept it.
So, I know that it is possible to add error handlers for specific error codes, e.g.:
app.add_error_handler(404, error.normalize)
app.add_error_handler(400, error.normalize)
However, for the 404 handler I manage to successfully intercept the error. But for the 400 (e.g. a json validation error) - the interception does not work.
How can I intercept each and every error that is sent from Connexion and change the json format, even if it is just to extend it like:
{
"detail": "Could not find page",
"error": {
"code": 404,
"message": "Could not find requested document."
},
"status": 404,
"title": "NotFound",
"type": "about:blank"
}
I use Connexion, with a 'tornado' server.
Thanks in advance.
Tom
With the latest version (connexion==2.5.1) this works for me:
from connexion import ProblemException
[...]
connexion_app.add_error_handler(400, render_http_exception)
connexion_app.add_error_handler(404, render_http_exception)
connexion_app.add_error_handler(ProblemException, render_problem_exception)
My exception handling functions:
from flask import jsonify
def render_http_exception(error):
resp = {
'error': {
'status': error.name,
'code': error.code,
'message': error.description,
}
}
return jsonify(resp), error.code
def render_problem_exception(error):
resp = {
'error': {
'status': error.title,
'code': error.status,
'message': error.detail,
}
}
return jsonify(resp), error.status
You can easily change it to your format.

Fiware-orion Remove all entities of the same type

I dont know what command pass to the Fiware Orion API(v2) to remove all element of an specific type. In this example fake.
I tried this, but it doesn't works :
response = self.PM.request(
method='post', url='http://127.0.0.1:1026/v2/op/update', headers={'Content-Type': 'application/json'},
body=json.dumps({
"actionType": "delete",
"entities": [{
"idPattern": ".*",
"type": "Fake",
}]
}))
I can remove the elements by ID. It is only a work around, but tells me that I am connecting correctly to the API. This is the code that works:
response = self.PM.request(
method='post', url='http://127.0.0.1:1026/v2/op/update', headers={'Content-Type': 'application/json'},
body=json.dumps({
"actionType": "delete",
"entities": [{
"id": "Fake1",
},
{
"id": "Fake2",
}
]}))
According to the docs this feature does not exist. Also, if you search the source code for "delete type" I don't see anything that matches. You'd need to do a select first and iterate through all the ids deleting them.
You are using some client in python to acess Orion Broker?

Python will not patch json in ConnectWise.

I am a little confused why the following will not work.
I am connecting to our ConnectWise API via requests. I get the response and then I parse through to find the tickets I am looking for. I am then trying to PATCH the ticket to change certain information.
Sample json that is returned via API.
{
"id": 12345,
"summary": "[CompanyName][ComputerName] Disk Space Check - drive G:",
"recordType": "ServiceTicket",
"board": {
"id": 1,
"name": "Board1",
},
"status": {
"id": 5,
"name": "NewTicket",
},
"owner": {
"id": 1,
"identifier": "",
Once I have identified the ticket I need to work with. I try to patch it.
def assign_ticket(self, ticket):
add_resource = [
{'op': 'replace', 'path': '/board/name', 'value': 'Board2'},
{'op': 'replace', 'path': '/status/name', 'value': 'NewTicket2'},
{'op': 'replace', 'path': '/owner/identifier', 'value': 'MyBrainHurts'}
]
r = requests.patch(self.url + self.url_ticket + str(ticket), json=add_resource, headers=self.header)
print(r.status_code)
It returns a 200 status code to indicate everything completely correctly, but only the /owner/identifier field is updated. The other two are not. I have Google'd for several days and tried multiple variations of the code but I do not see why it will not change the board or status. Any ideas?
I've just checked some of my other code and I'm patching successfully using an array, but I'm using the ID of the resource rather than the name. Try that; instead of /status/name use /status/id and a numerical value.
What is the result of r.text? That should either return the configuration in its new, patched, form or it will tell you why the patch didn't work.

PayPal Adaptive Payments - Preapproval request results in "Invalid request" error

I can't figure out what's happening with my Preapproval HTTP POST request. I'm just trying to do a basic call to PayPal's Adaptive Payments API, the Preapproval call specifically. And the PayPal error 580001 "Invalid request" is not that helpful in itself.
Request Headers (based on my Sandbox's account credentials, which I changed to xxx):
{
'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-PASSWORD': 'xxx',
'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-SIGNATURE': 'xxx',
'X-PAYPAL-SECURITY-USERID': 'xx',
'X-PAYPAL-APPLICATION-ID': 'APP-80W284485P519543T'
}
My request payload (HTTP POST, body encoded in JSON):
{
"requireInstantFundingSource": "TRUE",
"returnUrl": "http://www.google.com/?paypal=ok",
"maxTotalAmountOfAllPayments": 1002,
"maxNumberOfPaymentsPerPeriod": 1,
"endingDate": "2014-03-14T16:49:36+0000",
"requestEnvelope.errorLanguage": "en_US",
"clientDetails.applicationId": "XXX",
"cancelUrl": "http://www.google.com/paypal=cancel",
"startingDate": "2013-09-15T16:49:36+0000",
"feesPayer": "PRIMARYRECEIVER",
"currencyCode": "SEK"
}
The above POST body is posted to:
https://svcs.sandbox.paypal.com/AdaptivePayments/Preapproval
Response from Paypal ("prettified" for understanding):
{
"responseEnvelope": {
"ack": "Failure",
"timestamp": "2013-09-10T09:56:43.031-07:00",
"build": "6941298",
"correlationId": "26d55e6bfcaa0"
},
"error": [
{
"category": "Application",
"domain": "PLATFORM",
"severity": "Error",
"message": "Invalid request: {0}",
"subdomain": "Application",
"errorId": "580001"
}
]
}
Any feedback is appreciated.
OK fixed. How?
Fix #1
The arguments requestEnvelope.errorLanguage and clientDetails.applicationId need to be "JSONified" into objects on their own, such as:
"requestEnvelope": {
"errorLanguage": "en_US"
},
and
"clientDetails": {
"applicationId": "APP-XXXXXXXXXXXXX"
},
respectively.
Fix #2
Date formats; date format should be of the form 2014-03-15T20:14:38.007+00:00 and not 2014-03-14T20:14:38+0000 as I was passing. Note the milliseconds, and the timezone with the colon in the utc offset.
Next time an Invalid request comes up the parameters I'm passing will be the first thing to look at.

Categories

Resources