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.



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:

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
  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.

  1. Create a folder ‘nwrfcsdk’ in C:\
  2. Extract the contents of zip file ( 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: and saving it as ’’ file. Then go to the command prompt and run command ’python’. 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:
If by any chance the wget command above is not working, you can download the file [Source code (tar.gz)] from the url ( 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.

If you face any issues related to installation of NWRFCSDK or PyRFC, follow the troubleshooting guide on the github site ( 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 ( and Microsoft C++ Build Tools (

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 (

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

conn = Connection(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD)


options = [{ 'TEXT': "FCURR = 'USD'"}]
pp = PrettyPrinter(indent=4)
rowskips = 0
while True:
print("----Begin of Batch---")
result ='RFC_READ_TABLE', \
OPTIONS = options, \

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


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 (

from pyrfc import Connection
import re

class main():
def __init__(self):
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 = ''
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
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):

# 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)



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.


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!  🙂


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


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': '', 
      'sysnr': '00', 
      'saprouter': SAPROUTER, 
      'trace': '3' 
      c = get_connection(ABAP_SYSTEM)


  • 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.



    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?


  • 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.


    • 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.


    • Hello Unix Box ,

      I was able to locate the zip file on the URL you had provided. I logged into it with my S-user id and password and clicked on “SAP NW RFC SDK 7.50”. Currently, I do not have permissions to download the zip but you can reach to someone in your organization to help you download it.




      NWRFC SDK Download Screen


  • Do you know if there is a similar way to connect pyrfc towards SAP BW? is there a programmatic way in python to do it?


    Another question, is there a way using pyrfc to do the delta updates of SAP tables ?

    • Hello abdalrahman eweiwi ,

      If your BW system is on ABAP-stack and not on cloud then you can implement this on BW system as well. ?

      Regarding the delta updates, it is very much possible in SAP tables. The way I have pulled data from SAP, in a similar way you can push data towards SAP and update the tables.All you have to do is update the query and ensure you have read-write option available on the table.


  • Getting this error while executing connection
    UnicodeDecodeError                        Traceback (most recent call last)
    <ipython-input-11-fe97c46eb2cf> in <module>
         11             OPTIONS = options, \
         12             ROWSKIPS = rowskips,\
    ---> 13             ROWCOUNT = ROWS_AT_A_TIME)
         14         pp.pprint(result['DATA'])
         15         rowskips += ROWS_AT_A_TIME
    src\pyrfc\_pyrfc.pyx in
    src\pyrfc\_pyrfc.pyx in pyrfc.pyrfc.wrapResult()
    src\pyrfc\_pyrfc.pyx in pyrfc.pyrfc.wrapVariable()
    src\pyrfc\_pyrfc.pyx in pyrfc.pyrfc.wrapTable()
    src\pyrfc\_pyrfc.pyx in pyrfc.pyrfc.wrapStructure()
    src\pyrfc\_pyrfc.pyx in pyrfc.pyrfc.wrapString()
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf7 in position 3: invalid start byte
    • Hello ABHISHEK KUMAR  ,

      Please let me know if your issue was resolved.
      Are you working on one of the latest versions of Python i.e. 3.8.3 or above ?
      Please have a look at the response below from Srdjan Boskovic. It might be helpful for you.


  • Hi

    SDK PL - 7

    windows - 10

    python - 3.8.3

    pyrfc.whl- 2.0.0

    while running the code for TCURR copied from above, able to establish the connection successfully but while executing the call method i am getting the error for utf-8 decode. i am attaching the error screenshot. please help me out as soon as possible

  • First of all, I would like to thank you for the excelent manual.

    I am able to download data sunccessfully from SAP, however I am facing issues when I need to use more than one where clauses.

    When trying set more than one clause I am getting the following error:

    RFC_ABAP_RUNTIME_FAILURE (rc=3): key=SAPSQL_PARSE_ERROR, message=An error has occurred while parsing a dynamic entry

    What should be the correxct syntax to be used in that case:

    where = ['MATNR <> 0', 'EAN11 = 3526550004963'] - one of my attempts.
    Thanks a lot for all your support.
    • I have only used AND and it worked fine:

      where = [“MATNR <> 0 AND EAN11 = ‘3526550004963’”]

      And what is the solution to select data based on one field, like MATNR, with a set of different material codes in the WHERE clause? Is it possible to use a list? What is the correct syntax? just to clarify, I need to select from table MARC data from several material codes at once. 


      • The perfect scenario, in my cause, would be to have more than 4 clauses, and one of them allowing to check the values from a list. Do you know if is it possible?

        I need to download for COEP table all the values related to several OBJNR. How can I do it.


        Today my code is like that:

        # Choose your fields and table
        fields = ['KOKRS', 'PERIO', 'BELNR', 'OBJNR', 'GJAHR']
        table = 'COEP'
        # you need to put a where condition in there... could be anything
        where = ["GJAHR = 2021 AND KOKRS = 'H353' AND OBJNR starting 'KSH353MWMW09C10000'"]
  • Hi Arkesh Sharma,

    Thanks for very detail instruction to setup the environment for development, I did successfully connect to SAP and query the data. Now I need to manipulate (Create/Update) to following modules below on SAP via my application. Could you please share me any materials that can guide me to work with them ? Appreciate for your help.

    • Trading Contract(WB21, WB22, WB23)
    • Purchase Order (ME21N, ME22N, ME23N)
    • Delivery Order (VL01N, VL02N, VL03N, VL06F)


    Khoa Tran