Skip to Content
Technical Articles

Connecting Python with SAP (step-by-step guide)

Recently, a thought crossed my mind to connect Python with SAP as I am working in SAP Service Industry for couple of years and had been exploring Python for couple of months now. I found similar articles/blogs on it but then none of them covered the details. When I started with the initial setup, I realized that the information was scattered and bits & pieces of it were missing.

So, I decided to share my experience of how I actually went about doing it, what all problems/challenges I faced along the way and how I overcame those challenges.

I hope that readers after reading this blog will not face any challenges if they decide to pursue this task and this blog will help them save lot of time and efforts once they are done with it.

 

Introduction:

In this scenario, I am trying to establish a connection with SAP’s backend ECC system using a python code and trying to fetch the SAP table contents by calling the Function Module RFC_READ_TABLE.

You can use this code for variety of purposes from simply fetching the data from the SAP tables to analyzing the data for business purposes.

Mandatory Requirement:

To access SAP server, you need to make sure that SAP server is accessible/available on the network you’re are working on. If the SAP server is on a VPN or Citrix then this whole setup has to be done in that environment.

The prerequisite to connect to SAP is to install SAPNWRFC SDK and PyRFC on your machine so that you’re are able to establish a connection with SAP system.

The SDK installation is a tricky task. It is officially provided by SAP.
It needs to be downloaded and installed from the SAP’s website. The homepage of the SDK can be found here: https://support.sap.com/en/product/connectors/nwrfcsdk.html

Once the SAP’s NWRFCSDK is installed,you need to have PyRFC and Cython installed on the machine/system. This can be done via pip on command line. Build path also needs to be configured.


Installation (Step-By-Step):

Installation steps can be viewed in each of the sections below.

Please note that the steps mentioned below is for Windows 10 OS 64-bit only and does NOT cover steps for Mac or Linux.


Python Installation (Use latest version):

You need to follow the below steps to install Python on your machine. Make sure the windows user have the rights to configure the build path.

  1. Go to python.org
  2. Hover the mouse on ‘Downloads’
  3. Click on ‘All releases’
  4. Scroll down and select the latest release. In this case it is Python 3.8.3.
  5. Scroll down to the ‘Files’ section and select either ‘Windows x86-64 executable installer’ or ‘Windows x86-64 web-based installer’ (This is only for Windows 10 64-bit. If you’re on older version of windows then please choose accordingly.)
  6. The Python Installer will launch and follow the steps as mentioned in the installer. Make sure to add python to the build path as shown below:
  7. Once the installation completes, verify the version of python from the command prompt. Type ‘cmd’ in the search option and then type ‘python –version’ to see the version of the python installed.


    NWRFCSDK Installation (SAP website):

    You now have to visit the website in the link below to download the NWRFCSDK 7.50 from SAP’s site. Please make sure to choose the right version to download.  Its important to have a S-user for this purpose and permissions to download the software. Please contact the administrator of your organization if you do not have one. 

https://launchpad.support.sap.com/#/softwarecenter/template/products/_APP=00200682500000001943&_EVENT=DISPHIER&HEADER=Y&FUNCTIONBAR=N&EVENT=TREE&NE=NAVIGATE&ENR=01200314690100002214&V=MAINT

  1. Create a folder ‘nwrfcsdk’ in C:\
  2. Extract the contents of zip file (nwrfc750P_6-70002755.zip) in the path C:\nwrfcsdk
  3. You’ll see another nwrfcsdk folder inside C:\nwrfcsdk
  4. Cut and paste the contents from C:\nwrfcsdk\nwrfcsdk and move it to C:\nwrfcsdk folder
  5. Maintain the below user variable paths in the build PATH. Go to build PATH following the path as: Search (in bottom left corner) -> Control Panel -> System -> Advanced system settings -> Advanced (tab) -> Environment variables
    OR simply typing ‘environment’ in the search option next to windows logo
  6. Maintain the below system variable paths in the build PATH. Go to build PATH following the path as: Search (in bottom left corner) -> Control Panel -> System -> Advanced system settings -> Advanced (tab) -> Environment variables
    OR simply typing ‘environment’ in the search option next to windows logo

 

PyRFC & Cython Installation:

  1. There are couple of steps that need to be performed before you jump into installing pyRFC. The first of all is to confirm if you have pip installed on our machine. To check this you need to go to command prompt and type ‘pip show pip’If pip is not installed then you need to install pip by first getting pip by downloading the file from: https://bootstrap.pypa.io/get-pip.py and saving it as ’get-pip.py’ file. Then go to the command prompt and run command ’python get-pip.py’. Make sure you are in the directory of command prompt where the pip file is located
  2. To install Cython, you need to run the command ‘pip install cython’ from the command prompt and then cython will be installed

3.    You can proceed with the installation of PyRFC by typing the following command in command prompt:
‘wget https://github.com/SAP/PyRFC/releases/download/2.0.0/pyrfc-2.0.0-cp38-cp38-win_amd64.whl
If by any chance the wget command above is not working, you can download the file [Source code (tar.gz)] from the url (https://github.com/SAP/PyRFC/archive/2.0.4.tar.gz) and then place it in a folder and then install it by calling the pip command. You can type: ’pip install <complete file  path\file name>’. For example if the file is saved in Downloads folder, the complete command would be: ’pip install C:\Users\ArkeshSharma\Downloads\PyRFC-2.0.4.tar.gz’

  1. Once the installation is complete, type command ‘from pyrfc import connection’. If this runs properly, then it will not throw any errors and move on to a new command line. If it does not then it will throw an error. Based on the error you need to debug the issue by searching it in a browser or looking it up on GitHub.


Jupyter Notebook Installation:

  1. Type command ‘pip install jupyter’ on the command screen to install jupyter notebook
  2. Once that is done, run the tool by running the command ‘jupyter notebook’ from the command prompt. This will open an internet explorer screen for you.
  3. On the right side of the screen, go to the drop-down and click on ‘New’ and select ‘Python 3’
  4. Another tab will open up that will show the Jupyter screen. You can type the commands in the box and then run it by pressing the ‘Run’ button.

Once all the above steps are done, go to C:\nwrfcsdk\bin and double-click on rfcexec.exe file and see if it runs properly. If it does then a pop-up command prompt will appear for a while and then disappear. This indicates that the installation was successful.


Note-1:
If you face any issues related to installation of NWRFCSDK or PyRFC, follow the troubleshooting guide on the github site (https://sap.github.io/PyRFC/install.html). All issues are mostly resolved using the steps mentioned there. If there is anything else that is causing a problem then please feel free to leave a comment below.

Note-2: In certain cases, you might get errors related to missing Visual C++ libraries. Please make sure you have installed visual C++ Redistributable Package for Visual Studio 2013 (https://www.microsoft.com/en-US/download/details.aspx?id=40784) and Microsoft C++ Build Tools (https://aka.ms/buildtools)

In case you are not sure which libraries you need to download then you need to browse the error message and follow the steps mentioned in the forums.

 

Code Implementation:

I have written two different types of codes here to connect to SAP ECC system. Two different tables are called using the code. You can copy and paste the code as it is and then run it from the Jupyter screen. Make sure you make changes to the connection details (ASHOST, CLIENT, SYSNR, USER, PASSWD) of the parameters provided in the code.


CODE-1 (SAP’s TCURR Table):

This code accesses the TCURR table of SAP to fetch currency data from the table where the Currency is in USD. I am attaching the complete code below:

Complete Code (TCURR.py):


from pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError
from configparser import ConfigParser
from pprint import PrettyPrinter

ASHOST='sapxxxxx'
CLIENT='x00'
SYSNR='00'
USER='XXXXXXXX'
PASSWD='XXXXXXXX'
conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)

try:

options = [{ 'TEXT': "FCURR = 'USD'"}]
pp = PrettyPrinter(indent=4)
ROWS_AT_A_TIME = 10
rowskips = 0
while True:
print("----Begin of Batch---")
result = conn.call('RFC_READ_TABLE', \
QUERY_TABLE = 'TCURR', \
OPTIONS = options, \
ROWSKIPS = rowskips, ROWCOUNT = ROWS_AT_A_TIME)
pp.pprint(result['DATA'])

rowskips += ROWS_AT_A_TIME
if len(result['DATA']) < ROWS_AT_A_TIME:
break
except CommunicationError:
print("Could not connect to server.")
raise
except LogonError:
print("Could not log in. Wrong credentials?")
raise
except (ABAPApplicationError, ABAPRuntimeError):
print("An error occurred.")
raise

 

SAP Screen for TCURR Table:

Here is the homepage of SAP screen where we are going to the function module by typing the t-code SE37


Here we enter the name of the function module RFC_READ_TABLE and execute it.

After executing the Function Module, we get the below screen. We enter the values of the QUERY_TABLE and the DELIMITER as mentioned in the python code.

In the OPTIONS section we mention the condition FCURR = ‘USD’

We then execute the function module to get the results:

We see the output by clicking the table symbol next to the DATA Result: at the bottom.

OUTPUT of Python Code:

Here at the bottom of the screenshot after you run the code, you’ll see the output which is similar to the one you see in the SAP Screen above.


CODE-2 (SAP’s MEAN Table):

This code accesses the MEAN table of SAP to fetch first 10 rows of information from the table for the columns MATNR and EAN11. I am attaching the complete code below:

Complete Code (MEAN.py):

from pyrfc import Connection
import re

class main():
def __init__(self):
ASHOST='sapxxxxx'
CLIENT='x00'
SYSNR='00'
USER='XXXXXXXX'
PASSWD='XXXXXXXX'
self.conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)

def qry(self, Fields, SQLTable, Where = '', MaxRows=50, FromRow=0):
"""A function to query SAP with RFC_READ_TABLE"""

# By default, if you send a blank value for fields, you get all of them
# Therefore, we add a select all option, to better mimic SQL.
if Fields[0] == '*':
Fields = ''
else:
Fields = [{'FIELDNAME':x} for x in Fields] # Notice the format

# the WHERE part of the query is called "options"
options = [{'TEXT': x} for x in Where] # again, notice the format

# we set a maximum number of rows to return, because it's easy to do and
# greatly speeds up testing queries.
rowcount = MaxRows

# Here is the call to SAP's RFC_READ_TABLE
tables = self.conn.call("RFC_READ_TABLE", QUERY_TABLE=SQLTable, DELIMITER='|', FIELDS = Fields, \
OPTIONS=options, ROWCOUNT = MaxRows, ROWSKIPS=FromRow)

# We split out fields and fields_name to hold the data and the column names
fields = []
fields_name = []

data_fields = tables["DATA"] # pull the data part of the result set
data_names = tables["FIELDS"] # pull the field name part of the result set

headers = [x['FIELDNAME'] for x in data_names] # headers extraction
long_fields = len(data_fields) # data extraction
long_names = len(data_names) # full headers extraction if you want it

# now parse the data fields into a list
for line in range(0, long_fields):
fields.append(data_fields[line]["WA"].strip())

# for each line, split the list by the '|' separator
fields = [x.strip().split('|') for x in fields ]

# return the 2D list and the headers
return fields, headers

# Init the class and connect
# I find this can be very slow to do...
s = main()

# Choose your fields and table
fields = ['MATNR', 'EAN11']
table = 'MEAN'
# you need to put a where condition in there... could be anything
where = ['MATNR <> 0']

# max number of rows to return
maxrows = 10

# starting row to return
fromrow = 0
# Pretty Printer
pp = PrettyPrinter(indent=1)
# query SAP
results, headers = s.qry(fields, table, where, maxrows, fromrow)

print(headers)
pp.pprint(results)

 

SAP Screen for MEAN Table:

We follow the same steps as before. We launch the home page of SAP screen and execute the transaction SE37.


We enter the name of the function module RFC_READ_TABLE and execute it.

After executing the Function Module, we get the below screen. We enter the values of the QUERY_TABLE, ROWSKIPS and ROWCOUNT as mentioned in the python code.

In OPTIONS we mention the condition as MATNR <> ‘0’

In the FIELDS section we enter the two field names MATNR and EAN11 as mentioned in the python code:

We then execute it to get the below details:

OUTPUT of Python Code:

Here at the bottom of the screenshot after I ran the code, I see the output which is similar to the one I’ll see in the SAP Screen above.


Conclusion:

As seen from the two different codes above, after executing it in simple python editing tool like Jupyter Notebook, you’ll be able to successfully fetch the data from the SAP Tables (i.e. TCURR and MEAN).
You can use these python codes to simply fetch the data, display results or use the computational abilities of python for data analytics/ predictive analytics and send the results back to SAP ECC. The possibilities are endless!

So, what are you waiting for? Let’s get coding with Python!  🙂


References:

Below are some of the references that might help you give you an insight with the NW RFC SDK 7.50 and its functions along with the programming guide:

NW RFC SDK initial release notes and summary

Compile RFC Programs against NW RFC SDK 7.50

SAP NetWeaver RFC SDK Programming Guide

 

10 Comments
You must be Logged on to comment or reply to a post.
  • This is fantastic. Yes we dont find this information easily. lately I tried searching, it was scattered. Do share if you do some operations and put data back in SAP.

    • Thank you Pankaj for taking the time out and reading my article. I am sure you can update the SAP tables as well using Python code. However, as you know, hardcore SAP-ists will not allow to update/change/delete the data outside the SAP landscape. 😉
      I will look into the available options and write another blog for you. Thank you for the suggestion. Really appreciate it.

  • Thank you so much for this, Arkesh!

    It is going to be really helpful!

     

    Do you know how to setup a connection using Single Sign-On?

    • Hello Lior,

      Thank you for taking time out to read my article.

      You can access SAP with Single Sign-On using Python code while you’re logged onto the SAP system. You can try using the below code (and modifying it) to connect to the SAP SSO system:

      ABAP_SYSTEM = { 
      'snc_partnername': 'p:CN=I64, O=SAP-AG, C=DE', 
      'snc_lib': 'C:\\Program Files (x86)\\SECUDE\\OfficeSecurity\\secude.dll', 
      
      'name': 'I64', 
      'client': '800', 
      'ashost': '10.0.0.1', 
      'sysnr': '00', 
      'saprouter': SAPROUTER, 
      'trace': '3' 
      
      } 
      
      c = get_connection(ABAP_SYSTEM)

      //Arkesh

  • Hello Arkesh,

     

    Thank you for this well written document. My question is, is it possible to change NWRFSDK to Web

    Service if i need in the future. Am i have to modify my python code to adjust web service or can it be

    the same and used with web service instead of nwrfsdk as a functionally.

     

    Thanks,

    Sinan Akbas

    • Hello Sinan Akbas ,

      Thank you for going through my article. 🙂

      The objective here in this case is to connect to SAP backend using the python code and for that you need NWRFCSDK package on the system where you are running the python code. The end SAP ECC system needs to be on the same network where you are running the python code.

      It will be helpful if you can explain in more detail what you wish to do with the web service and why you need it?

      Regards,
      Arkesh

  • Hello Arkesh,

    Nice write-up, which I have yet to test.  Since Python relies on indentation, it is important to show that in the source code you have posted.  It might be that this website kills the indentation, so I suggest that you take a screenshot of the code from your own editor/IDE and paste them here.

    Thanks!

    • Thank you Kumar Sivagnanam for taking time to read my article. 🙂

      I agree with you that Python uses indentation in its code. However, as you can see from two screenshots of Jupyter Notebook, I have not used any indentation and still the code worked. So, I think in this case the indentation was not a requirement.

      Regards,
      Arkesh