Accessing NetSuite data with Python - python

Using Python, I would like to pull data from NetSuite, along with adding/updating data in NetSuite. For example, I would like to create sales orders and add line items via Python.
I'm aware that they have a WSDL that I could potentially use. (And I was hoping that they would also have an API, but apparently not...) Does anyone have examples working with this WSDL in Python? Are there better ways to integrate with NetSuite?

I have deal with Netsuite Webservice for around one week, there is not clear documentation but once you are align with the other regular webservices behaivour is very simple adapt yourself. I attach one little script to login and to get the full list of services and data types in netsuite.
Use the factory method to create the objects to interact with the netsuite webservice.
I have used suds as SOAP Python Library.
# -*- coding: utf-8 -*-
from suds.client import Client
import os, time, sys, datetime
import suds
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
reload(sys)
sys.setdefaultencoding('utf8')
NS_HOST = 'https://webservices.netsuite.com'
email ='myemail#xxxxxx.com'
pwd ='mypwd'
account = "99999999"
NS_ENDPOINT = "2016_2"
NS_ROLE = 3
wsdl = NS_HOST + "/wsdl/v" + NS_ENDPOINT + "_0/netsuite.wsdl"
client = Client(url=wsdl)
#You can get the methods and types with this object
print client
ApplicationInfo = client.factory.create('ns16:ApplicationInfo')
ApplicationInfo.applicationId = "xxxxx-XXXX-XXXX-XXXX-XXXXXXXX"
client.set_options(location= NS_HOST + "/services/NetSuitePort_" + NS_ENDPOINT, soapheaders={'applicationInfo':ApplicationInfo})
passport = client.factory.create('ns4:Passport')
passport.email = email
passport.password = pwd
passport.account = account
recordRef = client.factory.create('ns4:RecordRef')
recordRef.name="MX - Gerencia de Contabilidad"
passport.role = recordRef
client.service.login(passport)

Netsuite has provided toolkits for Java, .Net and PHP to access their webservices. For other languages either there are third party toolkits or you have to send Raw SOAP requests.
For my Python based projects I'm using Raw SOAP requests method. I suggest that first you get familiar with Netsuite Web services using any of the available toolkits and then for Python use this knowledge to generate raw SOAP requests. SOAPUI can also be of great help.
Have you explored restlets they are a generally good alternate for webservices.

There are a number of Python libraries available for processing SOAP messages, tried using SUDS, as it is the only one capable of properly consuming the 2014.1 Netsuite WSDL. This was only possible after some tweaks. The Netsuite WSDL is large and complex and took an enormous amount of time to load, even after caching AND loading from local. The SUDS library has not been maintained for quite a while, there is a maintained fork called SUDS-jurko that I have not yet tried. Ultimately, I ended up using raw soap messages to communicate with the Netsuite webservice for specific tasks.

Related

Package to build custom client to consume an API in Python based on a configuration file?

I am new to working with APIs in general and am writing code in python that needs to consume/interact with an API someone else has set up. I was wondering if there is any package out there that would build some sort of custom client class to interact with an API given a file outlining the API in some way (like a json or something where each available endpoint and http verb could be outlined in terms of stuff like allowed payload json schema for posts, general params allowed and their types, expected response json schema, the header key/value for a business verb, etc.). It would be helpful if I could have one master file outlining the endpoints available and then some package uses that to generate a client class we can use to consume the API as described.
In my googling most API packages I have found in python are much more focused on the generation of APIs but this isn't what I want.
Basically I believe you are looking for the built in requests package.
response = requests.get(f'{base_url}{endpoint}',
params={'foo': self.bar,
'foo_2':self.bar_2},
headers={'X-Api-Key': secret}
)
And from here, you can build you own class, pass it to a dataframe or whatever.
In the requests package is basically everything you need. Status handling, exception handling everything you need.
Please check the docs.
https://pypi.org/project/requests/

How to post request to API using only code?

I am developing a DAG to be scheduled on Apache Airflow which main porpuse will be to post survey data (on json format) to an API and then getting a response (the answers to the surveys). Since this whole process is going to be automated, every part of it has to be programmed in the DAG, so I canĀ“t use Postman or any similar app (unless there is a way to automate their usage, but I don't know if this is possible).
I was thinking of using the requests library for Python, and the function I've written for posting the json to the API looks like this:
def postFileToAPI(**context):
print('uploadFileToAPI() ------ ')
json_file = context['ti'].xcom_pull(task_ids='toJson') ## this pulls the json file from a previous task
print('--------------- Posting survey request to API')
r = requests.post('https://[request]', data = json_file)
(I haven't finished defining the http link for the request because my source data is incomplete.)
However, since this is my frst time working with APIs and the requests library, I don't know if this is enough. For example, I'm unsure if I need to provide a token from the API to perform the request.
I also don't know if there are other libraries that are better suited for this or that could be a good support.
In short: I don't know if what I'm doing will work as intended, what other information I need t provide my DAG or if there are any libraries to make my work easier.
The Python requests package that you're using is all you need, except if you're making a request that needs extra authorisation - then you should also import for example requests_jwt (then from requests_jwt import JWTAuth) if you're using JSON web tokens, or whatever relevant requests package corresponds for your authorisation style.
You make POST and GET requests and all individual requests separately.
Include the URL and data arguments as you have done and that should work!
You may also need headers and/or auth arguments to get through security,
eg for the GitLab api for a private repository you would include these extra arguments, where GITLAB_TOKEN is a GitLab web token.
```headers={'PRIVATE-TOKEN': GITLAB_TOKEN},
auth=JWTAuth(GITLAB_TOKEN)```
If you just try it it should work, if it doesn't work then test the API with curl requests directly in the Terminal, or let us know :)

Python - How to Send a Command to a Web Server

I have been in IT Support for many years but have always been interested in coding so I've started to train with Python. I'm working on a little coding project where I ask the user for some parameters (static IP to set for the camera, if the cam has a microphone, what they want camera to be named, etc) and then need to push these settings to an IP camera but I don't know how to "send" these commands to the IP of the camera.
For example, here's the command I run from a browser which will set the resolution on camera with IP 192.168.0.9x to 800x450:
http://192.168.0.9x/axis-cgi/param.cgi?action=update&Image.I0.Appearance.Resolution=800x450
How do I get Python to send these types of commands to a web server (the IP cam is essentially a web server)?
Thanks for any help :-)
L
Python-requests is an easy to use HTTP client.
To perform your request, start with:
import requests
params = { "Image.I0.Appearance.Resolution": "800x450",
"action": "update"
}
response = requests.get("http://192.168.0.9x/axis-cgi/param.cgi", params=params)
I think urllib2 is solution for your problem :)
import urllib2
content = urllib2.urlopen(some_url)
Look at requests. This is a third party library, but it's better than the built in urllib2.
import requests
r = requests.get(some_url)
Requests was developed with a few PEP 20 idioms in mind.
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Readability counts.
You could use webbrowser library in python to directly send the command to web page and control the camera. I used this for my FOSCAM FI8918W
for ur query it could be:
import webbrowser
webbrowser.open(http://192.168.0.9x/axis-cgi/param.cgi?action=update&Image.I0.Appearance.Resolution=800x450)
U can check the cgi commands from FOSCAM cgi reference guide

Explicit code generation from WSDL file for autocomplete?

I'm using the suds library as a SOAP client in some project.
I would like to know if there was a way to generate Python code according to the WSDL file.
For example, consider the following line to be from the WSDL file:
<operation name="GetLastTradePrice">
Then, I want to get in some .py file the auto-generated function
def GetLastTradePrice...
The purpose of that is to be able to know what are my possible functions and properties when I have a client. That means that if I will write:
from suds.client import Client
client = Client(SOME_URL)
Then, after typing the folloewing
client.service.
I will get the option of auto-completion GetLastTradePrice.
Ye olde ZSI library can generate Python code from a WSDL definition but, compared to suds, it's quite painful to use and requires another really old module called PyXML. I'd stick to suds, auto-completion isn't worth all that.
There are many SOAP server implementations for python, some more usable than others, search for packages related to SOAP at PyPI or take a look at the wiki page about web services at python.org. There are essentially two types of SOAP servers for python:
Servers that can generate server stubs from WSDL files (like ZSI)
Servers that can produce WSDL from the service class methods directly (like soaplib, ladon)

Python and curl question

I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
$xml= Some xml holding data of a purchase.
$curl = `/usr/bin/curl -s -d 'DATA=$xml' "https://url of the virtual bank POS"`;
$data=explode("\n",$curl); //return value is also an xml, seems like they are splitting by each `\n`
and using the $data, they process if the payment is accepted, rejected etc..
I want to achieve this under python language, for this I have done some searching and seems like there is a python curl application named pycurl yet I have no experience using curl and do not know if this is library is suitable for this task. Please keep in mind that as this transfer requires security, I will be using SSL.
Any suggestion will be appreciated.
Use of the standard library urllib2 module should be enough:
import urllib
import urllib2
request_data = urllib.urlencode({"DATA": xml})
response = urllib2.urlopen("https://url of the virtual bank POS", request_data)
response_data = response.read()
data = response_data.split('\n')
I assume that xml variable holds data to be sent.
Citing pycurl.sourceforge.net:
To sum up, PycURL is very fast (esp. for multiple concurrent operations) and very feature complete, but has a somewhat complex interface. If you need something simpler or prefer a pure Python module you might want to check out urllib2 and urlgrabber. There is also a good comparison of the various libraries.
Both curl and urllib2 can work with https so it's up to you.

Categories

Resources