bapi programming - sap help portal - the central place for sap

169
BAPI Programming HELP.CABFABAPIREF Release 4.6B

Upload: others

Post on 03-Feb-2022

30 views

Category:

Documents


0 download

TRANSCRIPT

BAPI Programming

HE

LP

.CA

BF

AB

AP

IRE

F

Re lease 4 .6B

BAPI Programming SAP AG

2 December 1999

Copyright

© Copyright 2000 SAP AG. All rights reserved.

No part of this brochure may be reproduced or transmitted in any form or for any purpose withoutthe express permission of SAP AG. The information contained herein may be changed withoutprior notice.

Some software products marketed by SAP AG and its distributors contain proprietary softwarecomponents of other software vendors.

Microsoft®, WINDOWS®, NT®, EXCEL®, Word® and SQL Server® are registered trademarks ofMicrosoft Corporation.

IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®,AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation.

ORACLE® is a registered trademark of ORACLE Corporation, California, USA.

INFORMIX®-OnLine for SAP and Informix® Dynamic ServerTM

are registered trademarks ofInformix Software Incorporated.

UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of The Open Group.

HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World WideWeb Consortium, Laboratory for Computer Science NE43-358, Massachusetts Institute ofTechnology, 545 Technology Square, Cambridge, MA 02139.

JAVA® is a registered trademark of Sun Microsystems, Inc. , 901 San Antonio Road, Palo Alto,CA 94303 USA.

JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license fortechnology invented and implemented by Netscape.

SAP, SAP Logo, mySAP.com, mySAP.com Marketplace, mySAP.com Workplace, mySAP.comBusiness Scenarios, mySAP.com Application Hosting, WebFlow, R/2, R/3, RIVA, ABAP, SAPBusiness Workflow, SAP EarlyWatch, SAP ArchiveLink, BAPI, SAPPHIRE, ManagementCockpit, SEM, are trademarks or registered trademarks of SAP AG in Germany and in severalother countries all over the world. All other products mentioned are trademarks or registeredtrademarks of their respective companies.

SAP AG BAPI Programming

December 1999 3

Icons

Icon Meaning

Caution

Example

Note

Recommendation

Syntax

Tip

BAPI Programming SAP AG

4 December 1999

Contents

BAPI Programming .............................................................................................6BAPI Programming Guide............................................................................................................. 7BAPIs .............................................................................................................................................. 9BOR............................................................................................................................................... 11Terminology ................................................................................................................................. 13Further Documentation on BAPIs.............................................................................................. 14Defining and Implementing the BAPI ........................................................................................ 15BAPI Explorer............................................................................................................................... 17

Working with Display Functions ............................................................................................... 18Working with Tools and Projects .............................................................................................. 20

Defining the Scenario.................................................................................................................. 21Reviewing the Scenario Concept............................................................................................... 23Defining a BAPI and Its Interface ............................................................................................... 24

Standardized BAPIs ................................................................................................................. 26Standardized Parameters......................................................................................................... 29Determining the Object Type and Its Key Fields...................................................................... 31Defining the Interface Structure of the BAPI ............................................................................ 32Naming Parameters in the Function Module ............................................................................ 34Defining Data Formats.............................................................................................................. 36Specifying Development Objects in ABAP Dictionary.............................................................. 37Naming the Method in the BOR ............................................................................................... 40Naming Parameters in the BOR............................................................................................... 41Naming the Function Module and the Function Module Group................................................ 43BAPIs Used for Outbound Processing ..................................................................................... 45

Creating Development Objects and Documentation ............................................................... 46BAPI Interface and Function Module......................................................................................... 48Testing the BAPI and Its Documentation .................................................................................. 52Releasing the BAPI...................................................................................................................... 53General Programming Guidelines for BAPIs ............................................................................ 54Transaction Model for Developing BAPIs ................................................................................. 58

BAPI Transaction Model with Commit...................................................................................... 60BAPI Transaction Model Without Commit ................................................................................ 63

Customer Enhancement Concept for BAPIs ............................................................................ 65Internal and External Data Formats ........................................................................................... 69Providing Input Help (F4 Help) ................................................................................................... 73Providing Interface Descriptions ............................................................................................... 75Buffering with Write BAPIs ......................................................................................................... 77

Example of Implementation and Process Flow ........................................................................ 83Improving Performance .............................................................................................................. 86Documentation Guidelines ......................................................................................................... 88Programming Standardized BAPIs ............................................................................................ 90Programming GetList() BAPIs.................................................................................................... 91

Example of a GetList() BAPI..................................................................................................... 92Programming GetDetail() BAPIs ................................................................................................ 93

SAP AG BAPI Programming

December 1999 5

Example of a GetDetail() BAPI................................................................................................. 94Programming GetStatus() BAPIs ............................................................................................... 96

Example of a GetStatus() BAPI................................................................................................ 97Programming ExistenceCheck() BAPIs..................................................................................... 98

Example of an ExistenceCheck() BAPI .................................................................................. 100Programming Create() BAPIs ................................................................................................... 102

Example of a Create() BAPI ................................................................................................... 104Programming Change() BAPIs ................................................................................................. 106

Example of a Change () BAPI ................................................................................................ 108Programming Delete() BAPIs.................................................................................................... 110

Example of a Delete() BAPI.................................................................................................... 112Programming Cancel() BAPIs................................................................................................... 113

Example of a Cancel() BAPI................................................................................................... 114Programming Replicate()/SaveReplica() BAPIs...................................................................... 115

Example of a SaveReplica() BAPI.......................................................................................... 118Programming Methods for Sub-Objects ................................................................................. 120Programming Standardized Parameters ................................................................................. 122Address Parameters.................................................................................................................. 123Change Parameters ................................................................................................................... 125Extension Parameters ............................................................................................................... 129Return Parameters (Error Handling)........................................................................................ 130Selection Parameters ................................................................................................................ 134TestRun Parameters.................................................................................................................. 135Text Transfer Parameters ......................................................................................................... 136Tools for Developing BAPIs ..................................................................................................... 137Defining Methods in the BOR Using BOR/BAPI Wizard ........................................................ 138Converting Internal and External Data Formats..................................................................... 140

Application Example ............................................................................................................... 142SAP Enhancements to Released BAPIs.................................................................................. 144Compatible Enhancements....................................................................................................... 146Incompatible Enhancements.................................................................................................... 148Customer Modifications and Developments........................................................................... 151BAPI Modifications .................................................................................................................... 152

Creating Subtypes .................................................................................................................. 156Redefining BAPIs ................................................................................................................... 157Defining Delegation Relationships ......................................................................................... 158

BAPI Development..................................................................................................................... 159Creating Subtypes .................................................................................................................. 160

Namespaces............................................................................................................................... 161Using BAPIs in Distributed Systems (ALE) ............................................................................ 164BAPI Quality Checklist .............................................................................................................. 166

BAPI Programming SAP AG

BAPI Programming

6 December 1999

BAPI Programming

SAP AG BAPI Programming

BAPI Programming Guide

December 1999 7

BAPI Programming GuidePurposeThis document describes the SAP guidelines for developing and implementing BusinessApplication Programming Interfaces [Page 9] (BAPIs). It is targeted at SAP developers and SAPpartners who want to implement BAPIs.

Customers are also recommended to follow these guidelines when developing BAPIs. Alldevelopments should be done in the customer name space; all changes to existingdevelopments objects of the SAP standard are considered to be modifications. (SeeNamespaces [Page 161]).

As these guidelines are targeted for internal use at SAP, procedures or tools may be mentionedthat do not apply or are not available to customers. Information that applies internally to SAP isindicated.

This document describes the guidelines valid at the time this document was published.

PrerequisitesTo program and implement a BAPI with these guidelines you need to have:

•••• Basic knowledge of BAPIs, as described in the BAPI User Guide [Ext.]

•••• Knowledge of the ABAP programming language and ABAP Workbench

•••• Basic knowledge of the R/3 System

Process FlowTo implement a BAPI follow the processes described in the sections below as closely aspossible:

Defining and Implementing the BAPI [Page 15]

Creating Development Objects and Documentation [Page 46]

General Programming Guidelines for BAPIs [Page 54]

Testing the BAPI and Its Documentation [Page 52]

Releasing the BAPI [Page 53]

Programming Standardized BAPIs [Page 90]

Programming Standardized Parameters [Page 122]

SAP Enhancements to Existing BAPIs [Page 144].

In Release 4.6A in the BAPI Explorer [Page 17] project forms are provided that takeyou step by step through the implementation procedure for BAPIs and enable you to

BAPI Programming SAP AG

BAPI Programming Guide

8 December 1999

document the development of your BAPIs. For SAP internal development it isobligatory to use a project form.

The BAPI Quality Checklist [Page 166] from earlier releases is still provided at theend of this document.

Other topics related to developing BAPIs are:

Modifications and Customers’ Own Developments [Page 151]

Using BAPIs in Distributed Systems (ALE) [Page 164]

SAP AG BAPI Programming

BAPIs

December 1999 9

BAPIsDefinitionA Business Application Programming Interface (BAPI) is a precisely defined interface providingaccess to processes and data in business application systems such as R/3.

BAPIs of SAP Business Object TypesBAPIs are defined as API methods of SAP business object types. These business object typesand their BAPIs are described and stored in the Business Object Repository [Page 11] (BOR). ABAPI is implemented as a function module, that is stored and described in the Function Builder.

BAPIs of SAP Interface TypesAs of Release 4.5A BAPIs can also describe interfaces, implemented outside the R/3 Systemthat can be called in external systems by R/3 Systems. These BAPIs are known as BAPIs usedfor outbound processing. The target system is determined for the BAPI call in the distributionmodel of Application Link Enabling (ALE).

BAPIs used for outbound processing are defined in the Business Object Repository (BOR) asAPI methods of SAP Interface Types. Functions implemented outside the R/3 System can bestandardized and made available as BAPIs. For further information see BAPIs Used ForOutbound Processing [Page 45].

IntegrationBAPIs can be called within the R/3 System from external application systems and otherprograms. BAPIs are the communication standard for business applications. BAPI interfacetechnology forms the basis for the following developments:

• Connecting:

• New R/3 components, for example, Advanced Planner and Optimizer (APO) and BusinessInformation Warehouse (BW).

• Non-SAP software

• Legacy systems

• Isolating components within the R/3 System in the context of Business Framework

• Distributed R/3 scenarios with asynchronous connections using Application LinkEnabling (ALE)

• Connecting R/3 Systems to the Internet using Internet Application Components (IACs)

• PC programs as frontends to the R/3 System, for example, Visual Basic (Microsoft) orVisual Age for Java (IBM).

• Workflow applications that extend beyond system boundaries

• Customers' and partners' own developments

The graphic below shows how BAPI interfaces enable different types of applications to be linkedtogether.

BAPI Programming SAP AG

BAPIs

10 December 1999

BAPIs - Interfaces to the R/3 System

Business Workflow

R/3 satellite systems /distributed systems (ALE)

Internet /Intranet

Customers and partners‘ own developments

VisualBasic/JAVA...

Isolating components in the Business Framework (R/3, R/2)

BBusiness

ComponentBusiness

Component

BusinessComponent

BusinessObject

BAPIBAPI

BusinessObject

BAPIBAPI

BusinessObject

BAPIBAPI

Business Object

BAPIBAPI

BAPIBAPI

BAPIBAPI

BusinessObject

BAPIBAPI

Business-Object

BAPIBAPI

For further background information on BAPIs refer to the document BAPI User Guide [Ext.].

SAP AG BAPI Programming

BOR

December 1999 11

BORDefinitionThe Business Object Repository (BOR) is the object-oriented repository in the R/3 System. Itcontains the SAP business object types and SAP interface types as well as their components,such as methods, attributes and events.

BAPIs are defined as methods of SAP business object types (or SAP interface types) in theBOR. Thus defined, the BAPIs become standard with full stability guarantees as regards theircontent and interface.

For general information on creating business objects see the documentation on SAP BusinessWorkflow [Ext.].

UseThe BOR has the following functions for SAP business object types and their BAPIs:

• Provides an object oriented view of R/3 System data and processes.

R/3 application functions are accessed using methods (BAPIs) of SAP Business Objects.Implementation information is encapsulated; only the interface functionality of the methodis visible to the user.

• Arranges the various interfaces in accordance with the component hierarchy, enablingfunctions to be searched and retrieved quickly and simply.

This finds the functionality searched for quickly and simply.

• Manages BAPIs in release updates.

BAPI interface enhancements made by adding parameters are recorded in the BOR.Previous interface versions can thus be reconstructed at any time. When a BAPI iscreated the release version of the new BAPI is recorded in the BOR. The same applieswhen any interface parameter is created.

The version control of the function module that a BAPI is based on is managed in theFunction Builder.

• Ensures interface stability.

Any interface changes that are carried out in the BOR, are automatically checked forsyntax compatibility against the associated development objects in the ABAP Dictionary.

IntegrationA BAPI is implemented as a function module, that is stored and described in the FunctionBuilder. You should only define a BAPI as a method of an SAP business object type in the BOR,if the function module that the BAPI is based on has been fully implemented.

Access to the BOR is restricted at SAP.

BOR/BAPI WizardThe BOR/BAPI Wizard [Page 138] helps you to create new BAPIs in the BOR. It takes youthrough the process step by step.

BAPI Programming SAP AG

BOR

12 December 1999

SAP AG BAPI Programming

Terminology

December 1999 13

TerminologyDefinitionThe table below contains definitions of the terms used in this document:

Term/Synonym Definition

Object type

Business object type

SAP business object type

Generic definition of business objects. Describes the generalcharacteristics and common attributes of instances of SAPbusiness object types.

Business object

Business object instance

SAP business objectinstance

One instance of an SAP business object type

BOR

Business Object Repository

Central repository within the R/3 System containing all thebusiness object types and SAP interface types together with theirdefinitions and methods.

BAPI

Business ApplicationProgramming Interface

Standardized programming interface enabling externalapplications to access business processes and data in the R/3System.

BAPIs are defined in the BOR as methods of SAP businessobject types that carry out specific business functions.

BAPIs are implemented as RFC-enabled function modules andare created in the Function Builder of the ABAP Workbench.

Interface type

SAP interface type

Definitions of attributes, methods and events grouped together inone context.An object type can support one or more interface types. Thefunctional group of associated attributes, methods and eventsdefined for the interface type together with their interfaces areused by the object type and are inherited by the respectivesubtypes of the object.

BAPI Programming SAP AG

Further Documentation on BAPIs

14 December 1999

Further Documentation on BAPIsIn the Open BAPI Network under the URL www.sap.com/bapi application developers can viewthe latest information on BAPI developments undertaken by SAP and by partners.

The following R/3 documentation contains further information about developing BAPIs anddeveloping with BAPIs:

Document

BAPI User Guide [Ext.] Information about using BAPIs in application programs.

BAPI Programming Guide[Page 7]

Describes how BAPIs are developed in SAP and whatguidelines you have to follow.

This document can also be used by customers and partners,who want to develop their own BAPIs, or enhance SAPBAPIs.

ALE Programming Guide [Ext.] Information about ALE technology (Application Link Enabling),including guidelines on using and programming BAPIsimplemented in ALE distributed environments.

Library of ALE BusinessProcesses [Ext.]

Overview of ALE business processes (application scenariosof Application Link Enabling). ALE business processesdelivered in the standard system are preconfigured andinclude important application examples of the distribution ofbusiness functions and processes.

BAPI ActiveX Control [Ext.] Describes how external client applications can use SAP’sBAPI ActiveX Control to access SAP business objects.

Calling BAPIs with BAPIControl [Ext.] in theTutorial: CommunicationInterfaces [Ext.]

Describes how business objects are called from the R/3System using SAP’s BAPI ActiveX Controls and how the datais displayed using Table View Controls

SAP Automation RFC andBAPI Interfaces [Ext.]

Describes how C++ and Java class libraries are used toaccess BAPIs on C++ and Java platforms.

R/3 DCOM ComponentConnector [Ext.]

Describes how the R/3 DCOM Component Connectordeveloped jointly by SAP and Microsoft is used to integrateR/3 objects and COM objects seamlessly. SAP businessobjects and their BAPIs can be called directly from COM-based development tools. COM components are alsoprovided in the SAP development environment.

The R/3 DCOM Component Connector SDK is shipped aspart of RFC SDK for Windows NT.

SAP AG BAPI Programming

Defining and Implementing the BAPI

December 1999 15

Defining and Implementing the BAPI

PurposeVarious components of the ABAP Workbench are used when you define and implement a BAPI.These are shown in the graphic below.

BAPIs are defined in the Business Object Repository (BOR) as API methods of SAP businessobject types. BAPIs are implemented in the Function Builder as RFC-enabled function modules.The definitions and descriptions of the data structures used by the BAPI are stored in the ABAPDictionary.

BOR, Function Builder and ABAP Dictionary

BusinessObject

Repository

Business Object BO:

Method 1 = M1

Method 2 = M2

ABAPWorkbench

FunctionBuilder

Function moduleBAPI_BO_M2

Function moduleBAPI_BO_M1

Definition anddescription ofdata structures

ABAPDictionary

PrerequisitesFor function modules that implement BAPIs, certain standards and rules must be adhered to overand above the standard programming rules for function modules.

The following sections guide you through the steps involved in developing a BAPI. The sectionscontain information about the guidelines and conventions that you should adhere to whendefining and implementing a BAPI. When implementing BAPIs follow the requirements below toensure you achieve consistent behavior and representation of BAPIs as object-oriented methodsof SAP business object types or SAP interface types.

BAPI Programming SAP AG

Defining and Implementing the BAPI

16 December 1999

Process FlowThe development of a BAPI is divided into the steps below (see also the appropriate projecttemplate in the BAPI Explorer [Page 17] or the BAPI Quality Checklist [Page 166]):

Task For further information see:

1. Defining the scenario in which the BAPIwill be used

Defining the Scenario [Page 21]

2. Reviewing the BAPI scenario and how theBAPIs interact with one another

Reviewing the Scenario Concept [Page 23]

3. Defining a BAPI and Its Interface Defining the BAPI and Its Interface [Page 24]

4. Creating individual programming objects Creating Development Objects andDocumentation [Page 46]

5. Programming BAPIs General Programming Guidelines for BAPIs[Page 54]

6. Testing the BAPI and its documentation Testing the BAPI and Its Documentation [Page52]

7. Releasing the BAPI Releasing the BAPI [Page 53]

8. Enhancing existing BAPIs, if required SAP Enhancements to Existing BAPIs [Page144]

SAP AG BAPI Programming

BAPI Explorer

December 1999 17

BAPI ExplorerDefinitionThe BAPI Explorer is the R/3 System working environment for developing BAPIs themselves andfor developing with BAPIs.

UsePrerequisitesThe BAPI Explorer is available as of Release 4.6A and enhances or replaces the BAPI Browserused in earlier releases. The BAPI Explorer uses the latest HTML control technology. For thisreason to work with the BAPI Explorer, you must be using a SAPgui of version 4.6A.

If you are using a SAPgui from an earlier release, the BAPI Browser (Transaction BAPI45) isautomatically called instead of the BAPI Explorer. For information about working in the BAPIBrowser see BAPI Browser [Ext.] in the BAPI User Guide.

PurposeIn the BAPI Explorer, application developers can get an overview of the status of BAPIs in theBOR. The BAPIs can be determined either by the position of the associated obect or interfacetype in the component hierarchy in the BOR, or from an alphabetical list. All information requiredto use a particular BAPI is provided in the BAPI Explorer.

The BAPI Explorer is used internally in SAP to develop BAPIs, but can also be used bycustomers and partners. The BAPI Explorer provides all the tools used to create BAPIs and therequired development objects in an integrated programming environment. The entiredevelopment process of a BAPI takes place in the framework of form-controlled "projects" toachieve maximum quality, stability and usability of the BAPI.

StructureThe BAPI Explorer is divided into two areas:

•••• Hierarchy display

Here all the business object types or interface types for which BAPIs have been definedare displayed. For further information see Working with Display Functions [Page 18].

•••• Work area

Here the details and documentation of the development object selected in the hierarchydisplay can be viewed.

The tools used to develop BAPIs are also available in the work area. For furtherinformation see Working with Tools and Projects [Page 20].

IntegrationTo call the BAPI Explorer choose Tools → Business Framework → BAPI Explorer. To call itdirectly use Transaction BAPI.

BAPI Programming SAP AG

Working with Display Functions

18 December 1999

Working with Display FunctionsUseIn the hierarchy display of the BAPI Explorer all the business object types or interface types forwhich BAPIs have been defined are displayed.

Using the tabs Alphabetical and Hierarchical in the hierarchy display, you can select whether thebusiness object types or interface types are displayed alphabetically or as they are assigned inthe component hierarchy in the BOR.

By expanding the relevant nodes you can navigate up to the parameter level of individual BAPIs.

FeaturesThe following display functions are also provided which enable you to directly access BAPIs andtheir details in the BOR.

•••• Displaying details

Under the Detail view of the work area all the technical details of the development objectselected in the hierarchy are displayed.

In most cases you can double-click on a field in the Detail display to get to thedevelopent environmnt or to display further information. For example, in the detail displayfor a particular method, by double clicking on the name of the function module, it will bedisplayed in the Function Builder.

•••• Displaying and Printing Documentation

In the Documentation view of the work area the documentation for the developmentobject selected in the hierarchy is displayed.

The data element documentation for each parameter field is contained in thedocumentation for structured BAPI parameters.

If you have installed Microsoft Internet Explorer Version 4.0 on the front-end computer,you can print the documentation using the standard SAPgui print function.

•••• Changing the level of the hierarchy display

The component hierarchy may have many hierarchy levels. To make it easier to find abusiness object type and its BAPIs, you can use the function Goto → Change hierarchylevel to limit the display to two hierarchy levels.

•••• Specifying the BAPIs to be displayed

The default is to display only released BAPIs of business object types. By choosing Goto→ BAPIs to display, you can display all the BAPIs contained in the BOR, that is BAPIs ofSAP interface types and BAPIs that have not yet been released.

Business object types and interface types are identified by different symbols. To displaythese, choose Goto → Display legend.

•••• Searching for BAPIs

Using the standard functions Find and Find next you can search the displayed businessobject types or interface types using specified criteria (placeholders such as ' * ' can beused):

SAP AG BAPI Programming

Working with Display Functions

December 1999 19

− Object name, e.g. BusinessProcess

− Object type (technical object name) e.g. SAP0001

− Object description, e.g. Plan*

− Method name, e.g. GetList

− Method description, e.g. object list*

BAPI Programming SAP AG

Working with Tools and Projects

20 December 1999

Working with Tools and ProjectsUseThe views Tools and Projects in the work area are mainly used for developing BAPIs.

FeaturesDepending on the development object selected in the hierarchy display, in the Tools view, thefollowing tools and navigation options are provided:

•••• Direct access to the Business Object Builder, Function Builder and ABAP Dictionary.

•••• List generator to create lists of BAPIs using specified selection criteria.

In the Project view you can create projects to assist you with following and documenting thedevelopment procedures below:

•••• Implementing new BAPIs (for internal SAP use, BAPI developments must be carried out anddocumented using a project in the BAPI Explorer)

•••• Changing released BAPIs (only for SAP internal use)

•••• Requesting a new business object type (only for SAP internal use)

For each of these projects there is a project form that takes you step by step through the entiredevelopment process and provides direct navigation options to the required development toolsand information.

Within the project management you can save and delete your projects and you can edit theprojects managed by other users by selecting Other users.

If you have installed Microsoft Internet Explorer Version 4.0 on the front-end computer, you canprint the project form using the standard SAPgui print function.

SAP AG BAPI Programming

Defining the Scenario

December 1999 21

Defining the ScenarioPurposeBefore you program a BAPI you should clearly define the processes and situations the BAPI willbe used for. BAPIs should only be implemented within the context of a meaningful businessscenario.

For examples of BAPI scenarios refer to Overview of ALE Integration Scenarios [Ext.] in theLibrary of ALE Business Processes. SAP developers will also find templates for defining anddocumenting BAPI scenarios.

Process FlowTo define the scenario the BAPI is to be used in, consider the following issues:

•••• Which scenario is to be implemented?

Every BAPI should be based on a model of a scenario in which it can be usefullyemployed.

Keep in mind whilst you are planning the scenario that COMMIT WORK commands mustnot be used in BAPIs. COMMIT WORK commands can adversely effect the process flowof the scenario and how the BAPIs in the scenario work together.=

•••• Which SAP business object types are required and do they exist?

From the scenario definition you can get information about the SAP business objecttypes relevant to the BAPI scenario. If the business object types required do not exist,they must be created. For information about creating SAP business object types see thedocumentation, SAP Business Workflow [Ext.]. For SAP internal development you haveto complete a business object request form in the BAPI Explorer.

A BAPI is required to read the data of a company code. First of all, a list of allcompany codes is to be displayed. From this list a company code can be selected,and then using another BAPI, details about this company code are to be displayed.

The relevant SAP business object type for this scenario is CompanyCode.

•••• What functionality should the BAPI provide and how does it affect related BAPIs, especiallythe other BAPIs of the SAP business object type in question?

In line with the scenario concept, BAPIs must complement each other to create acomplete scenario. Their relationships with each other must be clearly defined.

To read the details of a company code as described in the above example scenario,two BAPIs are required:

• To display all the company codes

• To display a specific company code

BAPI Programming SAP AG

Defining the Scenario

22 December 1999

The interdependency between these two BAPIs is evident because first the list ofcompany codes is displayed to obtain the ID of the specific company code sought.From this ID details of the company code can be displayed.

However, the two BAPIs remain functionally independent of each other, because ifthe company code ID is known, the BAPI "Display details of a specific companycode" can be used without first calling the BAPI "Display list of all company codes".

•••• To what extent can the BAPI's functionality be implemented within the scope of the businessobject?

A BAPI should be developed so that it provides functionality exclusively within thecontext of its associated SAP business object type. If the data of a different SAPbusiness object type is to be read or updated then the appropriate interface for thisobject type must be used. The functions or methods of these other object types are usedimplicitly.

The BAPIs required to read the details of a company code in the above examplescenario are only able to access data in the SAP business object typeCompanyCode. Other object types are not involved.

•••• Is the BAPI assigned to the SAP business object type in a meaningful and semanticallycorrect way?

ResultOnce you have considered these issues you will be able to clearly conceptualize the functionalityof the planned BAPI(s).You will also have identified the SAP business object types relevant to theBAPI scenario.

SAP AG BAPI Programming

Reviewing the Scenario Concept

December 1999 23

Reviewing the Scenario ConceptPurposeIn the previous step you created a concept for a scenario a BAPI could be applied to. You alsodefined the relevant SAP business object types.

Before you implement the scenario and begin defining and developing the BAPI, you shouldcarry out a review of the scenario.

Process FlowYou should carry out the review of the BAPI scenario together with all the people involved in thedevelopment of the BAPI and those responsible for quality control in your development group.

Confirm that the scenario as it stands is meaningful and that the BAPIs in the scenario caninteroperate without any problems.

Start developing the BAPI only after you have successfully completed the review.

BAPI Programming SAP AG

Defining a BAPI and Its Interface

24 December 1999

Defining a BAPI and Its InterfacePurposeAfter you have carried out the review of the BAPI concept and it has been accepted, you canstart defining the BAPI itself.

In this step, you will decide on the names, parameters, and characteristics of the BAPI anddetermine the structures in the ABAP Dictionary which the BAPI will be based on. Only after youhave planned and defined these required details can you start to implement the BAPI and createthe required programming objects.

The table below illustrates where the planned information is written and how it fits together.

Information in the BOR, Function Builder and ABAP Dictionary

Business Object Repository (BOR)Business object :

Interfaces :

Key fields :

Attributes :

Methods :

Parameters :

Events : ....

CompanyCode

....

CompanyCodeId

....

GetDetail

CompanyCodeDetail

CompanyCodeAddress

Return

Function BuilderBAPI_COMPANYCODE_GETDETAIL

COMPANYCODEID

COMPANYCODE_DETAIL

COMPANYCODE_ADDRESS

RETURN

Function module :

Parameter Importing :

Exporting :

ABAP DictionaryStructures

Fields

BAPI 0002_2

:

COMP_CODE

:

BAPI0002_3

:

BAPIRET2

:

Process FlowTo implement your BAPI in accordance with the required conventions, follow the guidelines foreach of the tasks below. Follow the instructions in the references given in the second column.

Task For further information see:

1. Check if the BAPI is in the Standardized BAPIscategory.

These BAPIs provide basic functions andcan be implemented for most of the SAPbusiness object types. Check whether theBAPI can be implemented as a standardizedBAPI.

Standardized BAPIs [Page 26]

SAP AG BAPI Programming

Defining a BAPI and Its Interface

December 1999 25

2. You have to identify the SAP business objecttype in the Business Object Repository or ifnecessary, create one.

Test whether the key fields of the businessobject type are relevant for your BAPI.

Determining the Object Type and ItsKey Fields [Page 31]

For information about creating SAPbusiness object types see thedocumentation, SAP BusinessWorkflow [Ext.].

3. Define the structure and the scope of the BAPIinterface

Defining the Interface Structure ofthe BAPI [Page 32]

and

Standardized Parameters [Page 29]

4. Give names to the required parameters in thefunction module.

Naming Parameters in the FunctionModule [Page 34]

5. Define the data formats in which the values mustbe transferred in the function module interface.

Defining Data Formats [Page 36]

6. Specify the required data objects in the ABAPDictionary.

Specifying Development Objects inthe Dictionary [Page 37]

7. Assign a name to the method in the BOR. Naming the Method in the BOR[Page 40]

8. Assign a name to the method parameter in theBOR.

Naming Parameters in the BOR[Page 41]

9. Specify the name of the function module that theBAPI is based on, and the name of the functiongroup in which the function module is to bestored.

Naming the Function Module and theFunction Module Group [Page 43]

ResultOnce you have completed these steps, you will have defined your BAPI.

BAPI Programming SAP AG

Standardized BAPIs

26 December 1999

Standardized BAPIsUseSome BAPIs and methods provide basic functions and can be used for most SAP businessobject types. Such BAPIs are known as “standardized” BAPIs.

FeaturesWith object methods and especially with BAPIs, you can differentiate between instancemethods and class methods. Instance methods refer to precisely one instance (one specificoccurrence) of an SAP Business Object type, for example, to one explicitly specified customerorder. Whereas class methods are instance-independent.

BAPIs for Reading DataThe following BAPIs provide you with read-only access to data in the associated business objecttype:

GetList()With the BAPI GetList() you can select a range of object key values, for example, companycodes and material numbers. The BAPIs GetList() is a class method.

For more information see Programming GetList() BAPIs [Page 91].

GetDetail()The BAPI GetDetail() uses a key to retrieve details about an instance (one specific occurrence)of a business object type and returns this data to the calling program. Then this information isreported back to the calling program. The BAPI GetDetail() is an instance method.

For more information see Programming GetDetail() BAPIs [Page 93].

GetStatus()The BAPI GetStatus() is used to query the status of an SAP business object instance, forexample, the processing status of a sales order. This BAPI is used only for displaying the statusof an object and does not retrieve full details like the BAPI GetDetail(). The BAPI GetStatus() isan instance method.

For more information see Programming GetStatus() BAPIs [Page 96].

ExistenceCheck()The BAPI ExistenceCheck() checks whether an entry exists for a business object instance, forexample, whether the customer master has been created. The ExistenceCheck() BAPI is aninstance method.

For more information see Programming ExistenceCheck() BAPIs [Page 98].

BAPIs for Creating or Changing DataThe following BAPIs can create, change or delete instances of a business object type:

SAP AG BAPI Programming

Standardized BAPIs

December 1999 27

Create() or CreateFromData()The BAPI Create() or CreateFromData() creates an instance of an SAP business object type, forexample, a purchase order. These BAPIs are class methods.

For more information see Programming Create() BAPIs [Page 102].

Change()The BAPI Change() changes an existing instance of a SAP business object type, for example, apurchase order. The () BAPI is an instance method.

For more information see Programming Change() BAPIs [Page 106].

Delete() and Undelete()

The BAPI Delete() deletes an instance of an SAP business object type from the database, forexample, a purchase order.

The BAPI Undelete() removes a deletion flag.

These BAPIs are instance methods.

For more information see Programming Delete() BAPIs [Page 110].

Cancel()Unlike the BAPI Delete () the BAPI Cancel() cancels an instance of a business object, that is theinstance to be cancelled remains in the database and an additional instance is created that iscanceled).

The Cancel() BAPI is an instance method.

For more information see Programming Cancel() BAPIs [Page 113].

Add<subobject> and Remove<sub-object>

The BAPI Add<sub-object> adds a sub-object to an existing object instance and the BAPI andRemove<sub-object> removes a sub-object from an object instance. These BAPIs are instancemethods.

For further information see Programming Methods for Sub-Objects [Page 120].

If you are implementing BAPIs that create or change data you should consider usingbuffering. For further information see Buffering for Write BAPIs [Page 77].

BAPIs for Mass ProcessingThe BAPIs listed in the above section, “BAPIs for Creating or Changing Data”, can also be usedfor mass processing. Here, when a BAPI is called, several business object instances areprocessed at the same time.

With BAPIs for mass processing, the suffix “Multiple” is added to the method name, for example,ChangeMultiple(), CreateMultiple(), DeleteMultiple(). The BAPIs here are always class methods.

BAPI Programming SAP AG

Standardized BAPIs

28 December 1999

We strongly recommend that you create instance-dependent BAPIs with bufferinginstead of Multiple() BAPIs. For further information see Buffering with Write BAPIs[Page 77].

BAPIs for Replicating Business Object InstancesThe following BAPIs are used for replicating business object instances:

Replicate() and SaveReplica()

The BAPIs Replicate() and SaveReplica() are implemented as methods of replicable businessobject types(). They enable specific instances of an object type to be copied to one or moredifferent systems. These BAPIs are used mainly to transfer data between distributed systemswithin the context of Application Link Enabling (ALE). These BAPIs are class methods.

For more information see Programming Replicate()/SaveReplica() BAPIs [Page 115].

SAP AG BAPI Programming

Standardized Parameters

December 1999 29

Standardized ParametersUseThere are some parameters that can be created for various BAPIs because they contain thesame or equivalent data in all BAPIs. Such parameters are known as “standardized” parameters.They should be implemented the same in all BAPIs.

FeaturesAddress parametersSpecific reference structures are defined for address parameters in BAPIs. You should copythese structures to use in your BAPI, especially if the underlying object type uses the centraladdress management (CAM).

For more information see Address Parameters [Page 123].

Change ParametersIn BAPIs that cause database changes (for example, Change() and Create() BAPIs) you must beable to distinguish between parameter fields that contain modified values and parameter fieldsthat have not been modified. This distinction is made through the use of standardizedparameters.

For more information see Change Parameters [Page 125].

Extension parametersThe parameters ExtensionIn and ExtensionOut provides customers with a mechanism thatenables BAPIs to be enhanced without modifications. For further information see CustomerEnhancement Concept for BAPIs [Page 65].

Return ParametersEach BAPI must have an export Return parameter for returning messages to the callingapplication. To provide application programmers with a consistent error handling process forBAPI calls, all Return parameters must be implemented in the same, standardized way.

For further information see Return Parameters (Error Handling) [Page 130].

Selection ParametersThe parameters in BAPIs used to search for specific instances of a business object type, forexample, BAPI GetList(), have to enable the caller of the BAPIs to specify appropriate selectioncriteria. Standardized selection parameters are used to do this.

For more information see Selection Parameters [Page 134].

Test Run ParametersThe parameter TestRun is used in the BAPIs that generate instances - Create() orCreateFromData(), to check the entries for the object instance in the database before actuallycreating the object instance. The creation of the object instance is only simulated and data is notupdated.

BAPI Programming SAP AG

Standardized Parameters

30 December 1999

For further information see Test Run Parameters [Page 135].

Text Transfer ParametersTo transfer BAPI documentation texts, for example, documentation of a business object type, youhave to create standardized text transfer parameters.

For more information see Text Transfer Parameters [Page 136].

SAP AG BAPI Programming

Determining the Object Type and Its Key Fields

December 1999 31

Determining the Object Type and Its Key FieldsPurposeObject typeYou have to identify the SAP business object type required for your BAPI in the Business ObjectRepository or if necessary, create one. For information about creating SAP business object typessee the documentation, SAP Business Workflow [Ext.]. For SAP internal development you haveto complete a business object request form in the BAPI Explorer.

Key FieldsA key is defined in the BOR for the majority of SAP business object types. This key may consistof several key fields which are used to identify an individual single instance of the SAP businessobject type.

You can differentiate between instance-dependent (instance methods) and instance-independent(class methods) BAPIs. Unlike instance-independent methods, instance-dependent methodsrelate to one instance (one specific occurrence) of an SAP business object type, for example toone specific sales order.

In the case of instance-dependent BAPIs, the key fields of the corresponding SAP businessobject type must be used as parameters in the function module the BAPI is based on so that theassociated object instance can be identified. For further information see Defining the InterfaceStructure of the BAPI [Page 32].

The names of the key fields in the SAP business object type and the corresponding parametersin the BAPI function module must be the same, because the name links the key fields to theparameters.

The SAP business object type, CompanyCode, has a key field namedCompanyCodeId.

This key field must be defined as a parameter with the name COMPANYCODEID inthe function modules of the instant-dependent BAPIs for this business object type.

Process FlowTo display a business object type and its key fields:

1. Select Tools →=ABAP Workbench → Overview →=Business Object Browser=. The businessobject types are displayed in the order of the R/3 application hierarchy.

2. Select the required SAP business object type in the application hierarchy and double click itto open it.

3. To display the business object type’s key fields, expand the node Key fields.

BAPI Programming SAP AG

Defining the Interface Structure of the BAPI

32 December 1999

Defining the Interface Structure of the BAPIPurposeIn this step you are going to define the scope and interface structure of the BAPI, that is, theindividual import, export and table parameters required for calling the BAPI. You will specify thenames of these parameters in the section Naming Parameters in the Function Module [Page 34]

You cannot use change and exception parameters in a function module whichimplements a BAPI.

Process FlowTry to structure the BAPI as clearly as possible. Match the import parameters with each other toavoid having redundant data in the interface.

To identify the interface parameters for your BAPI, proceed as follows:

1. Check that the key fields of the SAP business object type in question are required andspecify how they are going to be used in the BAPI interface. The key fields of the SAPbusiness object type are some of the most important BAPI parameters.

• If a key value is to be passed to the BAPI by the calling program, the key field mustbe set as an import parameter in the function module of the BAPI. That way aspecific instance of the business object type is identified.

For example, this could be a customer number (CustomerNo) in the BAPIsCustomer.GetDetail() and Customer.CheckPassword(), or the number of a salesdocument in the BAPI SalesOrder.GetStatus().

• For BAPIs that generate instances, for example, the BAPIs Create() orCreateFromData(), each key field of the business object type should be set as anexport parameter in the BAPI function module.

These BAPIs return one key value, for example, an order number in the BAPISalesOrder.CreateFromData().

• For BAPIs that are class methods no key field is set as the BAPI function module’sown parameter.

Class methods are instance-independent and are called without the use of keyvalues. Usually they return a table with a selection of key values. Exceptions arewrite BAPIs, as described in the list item above.

2. Specify what other data is relevant in import, export or table parameters for the BAPI.Check that the parameters can be implemented as standardized parameters.

You have to create an export parameter, Return, to send messages back to the callingprogram. For details see Return Parameters (Error Handling) [Page 130].

The BAPI to be developed is to read data from the SAP business object typeCompanyCode. To read the company code, the calling program has to specify the ID

SAP AG BAPI Programming

Defining the Interface Structure of the BAPI

December 1999 33

of the company code. The returned information should include detailed data andaddress data.

To map these requirements to the BAPI interface, the following parameters must becreated in the function module which the BAPI is based on:

• The key field CompanyCodeID of the SAP business object type as an importparameter

• A Return parameter that reports messages back to the calling program

• A parameter for the details of the company code.

• A parameter for the address data of the company code.

BAPI Programming SAP AG

Naming Parameters in the Function Module

34 December 1999

Naming Parameters in the Function ModulePurposeIn the previous step you identified the scope and the required contents of the interfaceparameters. Now you have to specify the names of these parameters in three function module.

Process FlowYou are only allowed to define export, import and table parameters for the BAPI function moduleinterface. Change and exception parameters are not allowed.

The names you choose for the function module parameters are used in the Business ObjectRepository (BOR) as the names of the associated method parameters. The names of BAPIparameters in the BOR and the names of the parameters in the associated function module mustbe identical. For this reason parameters in function modules must have meaningful names inEnglish to ensure the BAPI method call can be carried out without any problems.

When assigning parameter names follow the guidelines below:

• The names must be in English.

• As of Release 4.5A the names of method parameters in the BOR can be up to 30characters long. Parameter names in function modules that implement the BAPIs cantherefore also have up to 30 alphanumeric characters. (In earlier Releases names ofparameters in the BOR could only be a maximum of 20 characters long. The associatedparameter names in the function module could only be 20 characters long).

• Choose meaningful names and do not use abbreviations.

In the above example based on the company code scenario, the followingparameters were required:

• An import parameter for the key field CompanyCodeID of the SAP business object typeCompanyCode

• An export parameter for the detailed data of the company code.

• An export parameter for the address data of the company code.

• A return parameter that reports messages back to the calling program

You could use the following names for these parameters in the function module:Contents Name in Function Module Parameter TypeCompany code COMPANYCODEID IMPORTINGDetailed data of company code COMPANYCODEDETAIL EXPORTINGAddress data of company code COMPANYCODEADDRESS EXPORTINGReturn Parameters RETURN EXPORTING

SAP AG BAPI Programming

Naming Parameters in the Function Module

December 1999 35

BAPI Programming SAP AG

Defining Data Formats

36 December 1999

Defining Data FormatsPurposeHere you specify the formats in which the data has to be transferred in the function moduleinterface.

BAPIs are not end user interfaces, they are programming interfaces that can be used in diverseapplication areas, for instance, to connect non-SAP systems and PC products to the R/3 System.

Fields in BAPI parameters must be presented in a neutral form used in the database and not in aform formatted in the BAPI interface.

•••• Data must not be presented in a user-dependent or language-dependent format. Forexample, the date in a BAPI must be in the internally used format YYYYMMDD, where YYYYis the year, MM the month and DD the day.

•••• Standard codes, such as ISO codes must be used, whenever possible.

ExceptionsSAP-specific data formats must be converted into the data format required externally. Thisapplies to, for example:

•••• Currency amount fields

•••• Quantity fields

•••• Fields that have an internal key

•••• Specific fields in address structures

To do this you can generate function modules that can map the relevant data to each other andperform the conversion. For further information about these exceptions see Internal and ExternalData Formats [Page 69].

SAP AG BAPI Programming

Specifying Development Objects in ABAP Dictionary

December 1999 37

Specifying Development Objects in ABAP DictionaryPurposeAfter you have specified the contents and names of the required interface parameters, you canidentify and define the required data objects in the ABAP Dictionary.

Process FlowNote the following guidelines:

•••• You can use individual fields, structures and tables as parameters. Every parameter mustrefer to a Dictionary object.

Note that all the parameters must be defined as structures. If a parameter consists ofone field only, this must be linked to a field in a BAPI structure.

Complex data types, such as table fields in structures, are not allowed.

•••• You have to create your own data structures for the BAPI interface that are independent ofthe data structures generally used in the R/3 application. This enables changes to be madein R/3 applications without affecting BAPIs.

Give meaningful names to the data structures you create. Names should begin with theprefix BAPI.

•••• You must not use INCLUDE structures in BAPI structures, because enhancements toINCLUDE structures generally lead to incompatible changes to the BAPI structure. Forfurther information see Incompatible Enhancements [Page 148]. BAPI structures themselvesshould not be used in other structures.

Structure S1 consists of fields F1 and F2. Structure S2 includes structure S1 and has afield F3. If a field F3 is added to structure S1, this causes an incompatible change tostructure S2 and leads to a name clash of the F3 fields.

The graphic below illustrates the problem:

Original structures:Structure S1

Structure S2

Structure S1

Structure S2

Structures after adding field F3:

F1 F2

F1 F2 F3

F1 F2 F3

F1 F2 F3 F3

Problems in structure S2:• Field added in the middle ofstructure (incompatible change)• Two fields have the same name (naming conflict)

Structure S2 includes structure S1

•••• You can use existing data elements and domains for fields in BAPI structures. If possibleonly use central data elements and domains contained in Basis Development or inApplication Basis. The associated development classes begin with B or S.

BAPI Programming SAP AG

Specifying Development Objects in ABAP Dictionary

38 December 1999

Before you use an existing data element or domain, you should consult the respectivecolleague responsible for the object.

•••• Choose meaningful names in English for the fields in the structures. Up until Release 4.0 tencharacters were available for naming structures; from Release 4.0 you can use up to 30characters. You can use alphanumeric characters and underscores.

As of Release 4.0 default field names in English exist for data elements in the ABAPDictionary. Whenever possible use these names for the field and parameter names.

The report BBAPIFLD generates the English default names for the fields andparameters. To use this report refer to the report documentation.

If German field names are used in the internal work structures of a BAPI you can use thetransaction described in Converting Between Internal and External Data Formats [Page140], to convert the German field names into English.

In the example in the previous steps, the reference fields/tables shown below wereidentified for the parameters.

The first example here uses structures created in Release 3.1. In this Releasestructure names had a maximum of 10 characters.

The second example shows how you could name the structures more meaningfullyin Release 4.0.

Parameters and their Reference Fields in Release 3.1Parameter in the Function Module Reference Field/Table

COMPANYCODEID BAPI0002_2-COMP_CODE

COMPANYCODEDETAIL BAPI0002_2

COMPANYCODEADDRESS BAPI0002_2

RETURN BAPIRETURN1

Parameters and their Reference Fields in Release 4.0Parameter in the Function Module Reference Field/Table

COMPANYCODE BAPI0002_2-COMP_CODE

COMPANYCODEDETAIL BAPI0002_COMPANYCODEDETAIL

COMPANYCODEADDRESS BAPI0002_COMPANYCODEADDRESS

RETURN BAPIRETURN1

SAP AG BAPI Programming

Specifying Development Objects in ABAP Dictionary

December 1999 39

BAPI Programming SAP AG

Naming the Method in the BOR

40 December 1999

Naming the Method in the BORProcess FlowYou can now specify the name of the BAPI as a method of a SAP business object type in theBusiness Object Repository (BOR).

The individual components of BAPI names are identified by the use of upper and lower caseletters, for example, ChangePassword.

BAPI names must be meaningful and be in English, and can only have a maximum of 30characters. For example:

•••• ExistenceCheck

•••• ChangePassword

•••• GetDetail

For standardized BAPIs use the corresponding generic name, for example, GetList, GetDetail.For further information about these BAPIs see Standardized BAPIs [Page 26].

In standard, object-oriented language use, parentheses() are added to the methodname, for example GetList(), in documentation and user guides. This convention isalso used in the document.

However, no parentheses are used when assigning BAPI names.

To get an idea about naming BAPIs, you should take a look at the existing BAPIs of an SAPbusiness object type in the BOR.

SAP AG BAPI Programming

Naming Parameters in the BOR

December 1999 41

Naming Parameters in the BORProcess FlowYou can now assign names to the individual method parameters in the Business ObjectRepository (BOR).

These names are based on the names of the parameters in the function module that youassigned in Naming Parameters in the Function Module [Page 34].

When naming BAPI parameters in the BOR follow the guidelines below:

•••• The components of parameter names in the BOR are separated by upper and lower caseletters to make them easier to read. Each new word in the parameter name begins with acapital letter, for example, CompanyCodeDetail.

•••• From Release 4.0 the names of BAPI parameters in the BOR and the names of theparameters in the associated function module must be identical except for the use of upperand lower case letters. This was not necessarily the case for BAPIs developed beforeRelease 4.0.

•••• Standardized parameters have specified names. For more information see ProgrammingStandardized Parameters [Page 122].

If you create your BAPI in the BOR using the BOR/BAPI Wizard, the Wizard uses theparameter names in the function module as the default names of the methodparameters. For information about the BOR/BAPI Wizard see Defining Methods in theBOR Using the BOR/BAPI Wizard [Page 138].

•••• Parameter names in the BOR must be in English.

•••• Parameter names in the BOR cannot be more than 30 characters.

In the example in the previous steps, four parameters for one BAPI were identifiedand the names of these parameters specified in the function module.

The table below shows what the parameter names could look like in the functionmodule and in the BOR.

Parameters and their Names in the Function Module and in the BOR

Contents Name in Function Module Name in the BOR

Company code COMPANYCODE CompanyCode

Detailed data of companycode

COMPANYCODEDETAIL CompanyCodeDetail

Address data of companycode

COMPANYCODEADDRESS CompanyCodeAddress

Return Parameters RETURN Return

BAPI Programming SAP AG

Naming Parameters in the BOR

42 December 1999

SAP AG BAPI Programming

Naming the Function Module and the Function Module Group

December 1999 43

Naming the Function Module and the Function ModuleGroupPurposeHere you specify the name of the function module the BAPI is based on.

You must also specify the function group which this function module is to be assigned to. If thereis not an appropriate function group, you have to specify a name for a new function group.

Process FlowAssigning a Name to the Function ModuleChoose a name for the function module which gives an indication of what the BAPI is used for.

The naming convention for BAPIs is BAPI_<Name of object type>_<method name>. You cannotexceed the maximum length of 30 characters. If required, you can shorten the name of themethod, but the BAPI_<Name of object type> should always be written in full.

In the case of a GetDetail() BAPI, which reads details for the object typeCompanyCode, the name of the associated function module isBAPI_COMPANYCODE_GETDETAIL.

Specifying the Function GroupAll the BAPIs belonging to an SAP business object type should be created in one or morefunction groups. BAPIs belonging to different SAP business object types must not be created inthe same function group.

Ascertain whether a function group has already been created for the BAPIs of the SAP businessobject type in question. If a function group does not already exist, specify a name for one to becreated.

As the basis for naming the function group, you can use either the default technical name (objecttype) of the SAP business object type or its object name.

• The technical name (object type) of an SAP business object type usually takes the formof BUSnnnn, where n is a number. Use the suffix "nnnn" as the technical name of thefunction group. For example, if the technical name of the object type is BUS1008, thenthe associated BAPI function group is called 1008.

To find out the technical name of the business object type, open the object type in theBusiness Object Repository (BOR), as described in the section Determining the ObjectType and Its Key Fields [Page 31] To display further details, for example, the technicalname, double click on the name of the business object type .

• The object name of an SAP business object type can be used for the name of thefunction group. For example, all BAPIs associated with the business object type,CompanyCode, could be stored in a function group called Companycode.

BAPI Programming SAP AG

Naming the Function Module and the Function Module Group

44 December 1999

SAP AG BAPI Programming

BAPIs Used for Outbound Processing

December 1999 45

BAPIs Used for Outbound ProcessingUseAs of Release 4.5A BAPIs can also be defined which have been implemented outside the R/3System yet can still be called from the R/3 System.

These BAPIs are known as BAPIs used for outbound processing. Unlike the conventionalBAPIs that are implemented in the R/3 server system and also called here (inbound), outboundBAPIs are interfaces implemented on the client system. There are always separate systems fordefining (client) and for implementing (server) outbound BAPIs.

The target system is determined for the BAPI call in the distribution model of Application LinkEnabling (ALE).

IntegrationBAPIs used for outbound processing are defined in the Business Object Repository as APImethods of SAP interface types. Functions implemented outside the R/3 System can bestandardized and made available as BAPIs. BAPIs both for outbound processing and for inboundprocessing can be called in the same way via the ALE distribution model.

FeaturesWhen creating BAPIs for outbound processing keep in mind:

•••• BAPIs used for outbound processing simply require the interface definition; the functionmodule cannot be programmed.

•••• Use the BOR/BAPI Wizard to create a BAPI of an SAP interface type. For further informationsee Defining Methods in the BOR Using the BOR/BAPI Wizard [Page 138].

•••• In Release 4.5A API methods of interface types must have the status “implemented”.

•••• BAPIs used for outbound processing can be determined from the BOR using TransactionSWO1. For further information see Determining BAPIs of Interface Types [Ext.] in the BAPIUser Guide.

The information contained in the BAPI User Guide [Ext.] and in the BAPIProgramming Guide refers to - with the exception of the above-mentioned points -BAPIs of both SAP interface types and SAP business object types. If this is not thecase, the documentation will explain what the differences are.

BAPI Programming SAP AG

Creating Development Objects and Documentation

46 December 1999

Creating Development Objects and DocumentationPurposeAfter you have defined your BAPI, identified the relevant programming objects and given themnames, you can create the programming objects in the R/3 System.

Process Flow

Task Tools / Further Information

1. If necessary, create the required SAPbusiness object type in the Business ObjectRepository.

For SAP internal development you haveto complete a business object requestform in the BAPI Explorer.

For general information about creatingbusiness object types refer to thedocumentation on SAP BusinessWorkflow [Ext.].

2. The data objects, for example, structures,fields and domains are stored in the ABAPDictionary.

For further information see the ABAPDictionary [Ext.].

3. Create the function module in the FunctionBuilder and the function group, if required.

For further information see the BC -ABAP Workbench: Tools [Ext.].

4. Create the documentation for the BAPI andfor each interface parameter and for eachparameter field.

Documentation on the BAPI and itsparameters is essential because it is verydifficult to use a BAPI that has not beenwell documented.

For internal BAPI documentation youmust follow the current BAPIdocumentation guidelines which you canget from your contact person in the BAPIDevelopment group.

See the general DocumentationGuidelines [Page 88].

5. If required, generating the function modulesthat can convert between the internal andexternal data formats.

For details on how to do this seeConverting Between Internal andExternal Data Formats [Page 140].

6. Writing the program for the function modulethat the BAPI is based on.

Note that the COMMIT WORK commandmust not be used in the function module.

For further information see GeneralProgramming Guidelines for BAPIs[Page 54]andProgramming Standardized BAPIs[Page 90]

For an example of a function modulethat implements a BAPI see BAPIInterface and Function Module [Page48].

SAP AG BAPI Programming

Creating Development Objects and Documentation

December 1999 47

7. Using the BOR/BAPI Wizard, define thefunction module as a method of theassociated SAP business object type in theBOR.

Finally, make sure that the parametersand parameter types of the method in theBOR match the parameters of theunderlying function module in theFunction Builder.

For more information see DefiningMethods in the BOR Using theBOR/BAPI Wizard [Page 138].

For an example of a function modulethat implements a BAPI see BAPIInterface and Function Module [Page48].

BAPI Programming SAP AG

BAPI Interface and Function Module

48 December 1999

BAPI Interface and Function ModuleThe definition of a BAPI in the Business Object Repository and its associated function module inthe Function Builder must correspond to each other. This example shows the relationshipsbetween the method and the function module.

The graphic below shows the SAP business object type PurchaseOrder (BUS2012) in the BAPIBrowser view of the BOR. Note the following:

•••• The business object type has a key field PurchaseOrder.

•••• The method we are looking at, GetDetail(), displays details of a purchase order Themethod consists of several import, export, and import/export (table) parameters.

Business Object PurchaseOrder with Key Fields and Methods

Function Module BAPI_PO_GETDETAILThis function module BAPI_PO_GETDETAIL implements the BAPI GetDetail() of the businessobject type PurchaseOrder.

Keep in mind the following points when reading the source code extract below:

•••• The name of the function module BAPI_PO_GETDETAIL is in the format: BAPI_<Nameof object type>_<method name>. Standard abbreviations can be used for business

SAP AG BAPI Programming

BAPI Interface and Function Module

December 1999 49

object types. It is, however, better to write the name of the object type in full, for example,BAPI_PURCHASEORDER_GETDETAIL and, if necessary, to shorten the method name.

•••• BAPI data structures are used. These are recognized by the prefix BAPI, for example,BAPIEKKOL.

•••• As of Release 4.0 the names of the parameters in the method in the BOR must beexactly the same as the names of the parameters in the function module. Underscores inparameter names are no longer allowed.

•••• The key field PURCHASEORDER of the business object type is defined as an importparameter.

•••• The function module performs authorization checks.

•••• The function module picks up exceptions in the Return parameter. From Release 4.5Athe reference structure BAPIRET2 or BAPIRET1 must be used.

Source CodeFunction Module BAPI_PO_GETDETAIL*"----------------------------------------------------------------------*"*"local interface:*" IMPORTING*" VALUE(PURCHASEORDER) LIKE BAPIEKKO-PO_NUMBER*" VALUE(ITEMS) LIKE BAPIMMPARA-SELECTION DEFAULT 'X'*" VALUE(ACCOUNT_ASSIGNMENT) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE*" VALUE(SCHEDULES) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE*" VALUE(HISTORY) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE*" VALUE(ITEM_TEXTS) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE*" VALUE(HEADER_TEXTS) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE*" VALUE(SERVICES) LIKE BAPIMMPARA-SELECTION*" DEFAULT SPACE

*" EXPORTING*" VALUE(PO_HEADER) LIKE BAPIEKKOL STRUCTURE BAPIEKKOL*" VALUE(PO_ADDRESS) LIKE BAPIADDRESS*" STRUCTURE BAPIADDRESS

*" TABLES*" PO_HEADER_TEXTS STRUCTURE BAPIEKKOTX OPTIONAL*" PO_ITEMS STRUCTURE BAPIEKPO OPTIONAL*" PO_ITEM_ACCOUNT_ASSIGNMENT STRUCTURE BAPIEKKN*" OPTIONAL*" PO_ITEM_SCHEDULES STRUCTURE BAPIEKET OPTIONAL*" PO_ITEM_TEXTS STRUCTURE BAPIEKPOTX OPTIONAL*" PO_ITEM_HISTORY STRUCTURE BAPIEKBE OPTIONAL*" PO_ITEM_HISTORY_TOTALS STRUCTURE BAPIEKBES OPTIONAL*" PO_ITEM_LIMITS STRUCTURE BAPIESUH OPTIONAL*" PO_ITEM_CONTRACT_LIMITS STRUCTURE BAPIESUC OPTIONAL*" PO_ITEM_SERVICES STRUCTURE BAPIESLL OPTIONAL*" PO_ITEM_SRV_ACCASS_VALUES STRUCTURE BAPIESKL*" OPTIONAL*" RETURN STRUCTURE BAPIRETURN OPTIONAL

BAPI Programming SAP AG

BAPI Interface and Function Module

50 December 1999

*"----------------------------------------------------------------------

* reset all structures and tables

CLEAR: PO_HEADER, PO_ADDRESS, PO_ITEMS, PO_HEADER_TEXTS,PO_ITEM_ACCOUNT_ASSIGNMENT, PO_ITEM_SCHEDULES,PO_ITEM_TEXTS, RETURN, EKPOKEY, PO_ITEM_HISTORY,PO_ITEM_HISTORY_TOTALS, PO_ITEM_LIMITS, PO_ITEM_SERVICES,PO_ITEM_CONTRACT_LIMITS, PO_ITEM_SRV_ACCASS_VALUES,CEKKO, CEKPO, CEKKN, CEKET, CEKAN, SEKKO, SEKPO, CADR.

REFRESH:PO_HEADER_TEXTS, PO_ITEM_ACCOUNT_ASSIGNMENT, PO_ITEM_SCHEDULES,PO_ITEM_TEXTS, PO_ITEMS, RETURN, EKPOKEY, PO_ITEM_HISTORY,PO_ITEM_HISTORY_TOTALS, PO_ITEM_LIMITS, PO_ITEM_SERVICES,PO_ITEM_CONTRACT_LIMITS, PO_ITEM_SRV_ACCASS_VALUES,CEKKN, CEKET, SEKKO, SEKPO.

* select the header data from database

SELECT SINGLE * FROM EKKO WHERE EBELN EQ PURCHASEORDER.IF SY-SUBRC NE 0.

PERFORM FILL_BAPIRETURN TABLES RETURNUSING 'E'

'W5''107'PURCHASEORDERSPACESPACESPACE.

EXIT.ENDIF.

* authority check

PERFORM PO_AUTHORITY_HEADER TABLES RETURNUSING EKKO.

IF NO_AUTHORITY NE SPACE.PERFORM FILL_BAPIRETURN TABLES RETURN

USING 'E''W5''033'SPACESPACESPACESPACE.

EXIT.ENDIF.

…….

…….

SORT PO_ITEMS BY PO_NUMBER PO_ITEM.SORT PO_ITEM_ACCOUNT_ASSIGNMENT BY PO_ITEM SERIAL_NO.SORT PO_ITEM_SCHEDULES BY PO_ITEM SERIAL_NO.SORT PO_ITEM_HISTORY BY PO_ITEM SERIAL_NO.SORT PO_ITEM_HISTORY_TOTALS BY PO_ITEM SERIAL_NO.SORT PO_ITEM_LIMITS BY PCKG_NOSORT PO_ITEM_CONTRACT_LIMITS BY PCKG_NO LINE_NO.SORT PO_ITEM_SERVICES BY PCKG_NO LINE_NO.SORT PO_ITEM_SRV_ACCASS_VALUES BY PCKG_NO LINE_NO SERNO_LINE.

ENDFUNCTION.

SAP AG BAPI Programming

BAPI Interface and Function Module

December 1999 51

BAPI Programming SAP AG

Testing the BAPI and Its Documentation

52 December 1999

Testing the BAPI and Its Documentation

PurposeAfter you have implemented the function module your BAPI is based on and you have definedthe BAPI as a method of an SAP business object type in the Business Object Repository (BOR)you should check that the BAPI functions properly.

PrerequisitesCarry out the test together with persons responsible for quality control in your developmentgroup.

Before you start testing make sure that the underlying function module has been completelyimplemented and that the BAPI has been correctly defined in the BOR as method of a businessobject type.

Process FlowTesting the DocumentationCheck that the documentation for each business object type, each BAPI and for each interfaceparameter is available and that you can understand it.

Testing the BAPIYou can test the BAPI in the following ways:

•••• By testing the underlying function module in the Function Builder

You can individually test the parameters in your function module by entering theappropriate test values in the parameters to verify that the source code in the functionmodule can run without errors.

•••• By testing the BAPI call from an external program.

You should ensure that your BAPI can be called from within external programs, forexample, from a Visual Basic program using SAP’s BAPI ActiveX Control [Ext.].

ResultIf you find any errors in the BAPI implementation, correct them and repeat the tests until you andthe quality control team in your group are fully satisfied with the BAPI implementation and withthe documentation.

SAP AG BAPI Programming

Releasing the BAPI

December 1999 53

Releasing the BAPIAfter you have completed the function module and BAPI tests, the development of the BAPI iscomplete.

You can now release the function module the BAPI is based on and the method in the BusinessObject Repository (BOR).

Once the BAPI has been released, it becomes available as a fully implemented method of abusiness object type. Releasing also prevents anyone making incompatible changes to the BAPI,because all changes made to a released BAPI are automatically checked for compatibility in theBOR and the ABAP Dictionary, and incompatible changes are rejected. For more informationabout what to look out for when making changes to existing BAPIs see SAP Enhancements toExisting BAPIs [Page 144].

The BAPI must be released in cooperation and agreement with the persons responsible for thedevelopment objects involved and those responsible for quality control.

To release a BAPI follow the steps below:

1. First release the function module in the Function Builder. SelectFunction module → Release → Release.

2. Set the status of the method to 'released' in the Business Object Builder.

3. Select the relevant SAP business object type in the Business Object Builder and openthe node Methods.

4. Place the cursor on your BAPI and select Edit → Change release status → Object typecomponent → In Released.

5. Verify the new status of the function module in the Function Builder and the method inthe BOR.

Releasing BAPIs in the Context of ALEIf you are implementing the BAPI in an asynchronous context of Application Link Enabling (ALE),you have to also release the IDoc associated with the BAPI. For more information see the ALEProgramming Guide [Ext.].

BAPI Programming SAP AG

General Programming Guidelines for BAPIs

54 December 1999

General Programming Guidelines for BAPIsUseTo ensure that BAPIs, as interfaces of SAP business object types, provide access to R/3 dataand processes in a consistent way, you must follow certain rules when programming BAPIs. Thissection contains general information and guidelines on programming BAPIs.

It is difficult to formalize the contents and functional scope of a BAPI. Every BAPI has a differentfunctional content, even those that perform similar functions, for example, the standardizedBAPIs. The differences are mainly due to the different characteristics of SAP business objecttypes and their contents.

Guidelines Specific to BAPIsIn addition to the general guidelines, you should follow the specific guidelines for programmingBAPIs:

Programming Standardized BAPIs [Page 90]

Using BAPIs in Distributed Systems (ALE) [Page 164]

General RecommendationsKeep in mind the following recommendations when developing your BAPI:

Recommendation For Further Information See:

Minimize interface complexity.

Supply the BAPI with the minimum of data and group thedata from a business perspective.

Structure your BAPI in the most efficient way Improving Performance [Page 86]

Mandatory RulesYou must follow these rules for all BAPIs:

General Mandatory Rules For Further Information See:

BAPIs must not invoke COMMIT WORKcommands.

Transaction Model for Developing BAPIs[Page 58]

BAPIs must not contain the following commands:

• CALL TRANSACTION

• SUBMIT REPORT

• SUBMIT REPORT AND RETURN

Transaction Model for Developing BAPIs[Page 58]

INCLUDE structures must not be used in BAPIstructures.

Specifying Development Objects in theDictionary [Page 37]

SAP AG BAPI Programming

General Programming Guidelines for BAPIs

December 1999 55

Database changes can only be made throughupdates.

Transaction Model for BAPIs WithoutCommit [Page 63]

The global memory must not be used to transfervalues.

Transaction Model for Developing BAPIs[Page 58]

Due to transparency it is strongly recommendednot to use Set and Get.

Transaction Model for Developing BAPIs[Page 58]

If required every BAPI must be able to carry outits own authorization checks.

Values relevant for Customizing are not allowedto be changed.

Programming Create() BAPIs [Page 102]and Programming Change() BAPIs [Page106]

Language-dependent values cannot be used asinterface parameters.

BAPIs must not produce any screen output. Thismeans that lists, queries and dialog boxes mustnot be returned to the calling program. This istrue for the BAPI itself and for any functionmodule that may be indirectly called by the BAPI.

BAPIs must not cause program terminations,they can only return a message (type A:termination message) in the return parameter.Messages of type E (error) and A (termination)cannot be output in the program.

Return Parameters (Reporting Errors) [Page130]

Fields and ParametersYou must follow these rules for BAPI fields and parameters:

Mandatory Rules for Fields and Parameters For Further Information See:

Standardized parameters must be implementedconsistently.

Programming Standardized Parameters[Page 122]

Each BAPI must have a return parameter forreturning messages to the calling application.

Return Parameters (Reporting Errors) [Page130]

All field and parameter names must be in English Naming Parameters in the Function Module[Page 34]

Specifying Development Objects in theDictionary [Page 37]

All quantity and amount fields must be assignedquantity unit fields.All currency amount fields must be assignedcurrency IDs.

Internal and External Data Formats [Page69]

All key fields in GetDetail() and GetList() BAPIsmust be displayed as text fields.

BAPI Programming SAP AG

General Programming Guidelines for BAPIs

56 December 1999

Whenever possible, F4 input help for fields inBAPI parameters must be made available

Providing Input Help (F4 Help) [Page 73]

Data conversionYou must follow these rules for data conversions:

Mandatory Rules for Data Conversion For Further Information See:

Only the internal data format can be used inBAPIs

Except for:

• Currency amount fields

• Quantity fields

• ISO codes

• Fields that have an internal key

• Specific fields in address structures

Internal and External Data Formats [Page69]

You must always use a period for the decimalpoint

Currency amounts with decimal points must beformatted with a decimal point in the interface.

For example, the value "10.12" must be formattedas "10.12" and not as "1012".

Internal and External Data Formats [Page69]

DocumentationYou must follow these rules for the documentation:

Mandatory Rules for Documentation For Further Information See:

The business object type must be documented Business object type documentation isstored in the Business Object Repository.

SAP information developers must follow thelatest business object type documentationguidelines. You can get these from yourcontact person in BAPI development.

SAP AG BAPI Programming

General Programming Guidelines for BAPIs

December 1999 57

The business object must be documented

All interface parameters must be documented.

Note the following guidelines:

•••• BAPIs with buffering must be identified as

such.«•••• In the case of exceptions: If the BAPI

contains a COMMIT WORK command; thismust be documented.

•••• The documentation on return parametersmust describe all possible return values andmessages.

•••• If, for termination messages, a databaserollback is executed in the return parameter,this must be explained in the documentationon the return parameter.

•••• Documentation on mandatory parametersmust specify which fields must be filled.

•••• All mandatory fields in a parameter must bedocumented as mandatory parameters.

•••• All available BAPI table extensions must belisted in the documentation on the extensionparameter.

The documentation on the BAPI and theinterface parameters is created in theFunction Builder for the function module thatthe BAPI is based on.

SAP information developers must follow thelatest BAPI documentation guidelines. Youcan get these from your contact person inBAPI development.

Data element documentation must be written forall the fields in BAPI parameters.

Providing Interface Descriptions [Page 75]

The documentation must be checked forcompleteness and comprehensibility.

BAPI Programming SAP AG

Transaction Model for Developing BAPIs

58 December 1999

Transaction Model for Developing BAPIsUseThe transaction model in which BAPIs are used determines how you have to program BAPIs.

Logical Unit of Work (LUW) and StatelessnessWithin the context of the transaction model used to develop BAPIs, a transaction represents oneprocessing step or one logical unit of work (LUW). An R/3 LUW is all the steps involved in atransaction including updating the database.

The whole transaction must be programmed to be stateless.

The ACID principle applies to transaction models, meaning that transactions are:

•••• Atomic

When a transaction is called, database operations are either fully executed or not at all.Either all relevant data has to be changed in the database or none at all.

•••• Consistent

If a transaction is called more than once, each call must have the same result. No data isimported that may indirectly affect the result.

•••• Isolated (isoliert)

There must be no functional dependencies between two transactions, one transactionmust not affect another transaction.

•••• Durable

Changes cannot be reversed and transactions cannot be canceled.

FeaturesIn Release 3.1, the BAPIs themselves executed the COMMIT WORK command, BAPIs had thesame purpose as an LUW or transaction.

If a BAPI executes a COMMIT WORK command, this must be mentioned in the BAPIdocumentation. This is the only way users are able to know that the BAPI contains aCOMMIT WORK command.

These BAPIs must also be documented in the SAPNet - R/3 Frontend in Note0131838, "Collective Note for BAPIs with the Commit Work Command".

As of Release 4.0 BAPIs cannot execute 'COMMIT WORK' commands. This enables severalBAPIs to be combined in one LUW.

The outcome is two transaction models:

Transaction Model for BAPIs with Commit [Page 60]

Transaction Model for BAPIs Without Commit [Page 63]

SAP AG BAPI Programming

Transaction Model for Developing BAPIs

December 1999 59

BAPI Programming SAP AG

BAPI Transaction Model with Commit

60 December 1999

BAPI Transaction Model with CommitUseThe example below of an external program calling a BAPI to change data in an R/3 System,illustrates how the transaction model affects BAPI development using commit. For example, thiscould involve a transaction implemented with Visual Basic. Only data from the R/3 System is tobe changed.

The RFC connection is live the whole time the external program is logged on to the R/3 Systemto avoid having to connect and disconnect repeatedly. When the RFC connection is alreadyestablished, an RFC call does not essentially take up any more CPU time than a direct call to thefunction module from within the R/3 System.

There is one BAPI call for each transaction in this transaction model. BAPIs can only be calledsynchronously. A BAPI call is essentially the call of the underlying RFC capable function module.

The process flow of the program consists of the following steps below (see graphic below):

Log on

... Source code

Call BAPI to read and/or change data

... Source code

Call BAPI to read and/or change data

... Source code

Log off

SAP AG BAPI Programming

BAPI Transaction Model with Commit

December 1999 61

BAPI Transaction Model with Commit

R/3(ABAP). . .

Visual Basic

BAPI call (RFC call of function module)

Log on

. . .

Log off

. . .

Logical Unit of Work

. . .

Logical Unit of Work

RFC session

“Commit Work“ call

Time

What do the terms "LUW" and "stateless" mean to BAPIs that have been implemented in theframework of this transaction model?

If a transaction represents one Logical Unit of Work and in addition is supposed to be stateless,BAPIs are affected as follows:

•••• Initial state each time a BAPI is called

A repeated call of one BAPI must produce the same result. Only data that is not affectedby the execution of the BAPI, for example, Customizing data, can be buffered.

For BAPIs this means, for example, that due to transparency, Set and Get parametersand the global memory should not be used.

However, you can keep Customizing data in a global memory as this data remainsunchanged even if transaction calls are repeated.

•••• All or nothing principle

A database change, for example, creating a new sales order, must be carried outcompletely or not at all (LUW).

This is why BAPIs to be implemented in 3.1 are created with integrated commit control.The COMMIT WORK command is always invoked at the end of the function module of aBAPI that modifies data.

If a BAPI executes a COMMIT WORK command, this must be mentioned in the BAPIdocumentation. This is the only way users are able to know that the BAPI contains aCOMMIT WORK command.

BAPI Programming SAP AG

BAPI Transaction Model with Commit

62 December 1999

In later releases BAPIs can only be implemented with integrated COMMIT WORKcommands in exceptional cases. BAPIs with COMMIT WORK must be documentedin the SAPNet - R/3 Frontend in Note 0131838, "Collective Note for BAPIs with theCommit Work Command".

•••• No functional dependency between two BAPIs

A BAPI call must not be negatively affected by an earlier call of another BAPI. A followup call must not presuppose an earlier call. For this reason also, you should not use Setand Get parameters in the BAPI nor use the global memory.

Make sure that a COMMIT WORK command only deletes the memory of the functionmodule, and not the memory of the function group. The global data of the function groupremains and could prevent another BAPI from being called, and thus impair the BAPI’sfunctional independence.

•••• Other separate LUWs are not triggered

The call of a BAPI must not trigger further LUWs that are independent of the BAPI. Forthis reason BAPIs must not contain the following commands:

•••• CALL TRANSACTION

•••• SUBMIT REPORT

•••• SUBMIT REPORT AND RETURN

SAP AG BAPI Programming

BAPI Transaction Model Without Commit

December 1999 63

BAPI Transaction Model Without CommitUseAs of Release 4.0 the commit control must be taken out of write BAPIs, that is, those BAPIs thatcause database changes. The existing transaction model should not be changed. This isachieved by using the method TransactionCommit of the business object type BapiService whichexecutes the command COMMIT WORK.

The process flow of the program consists of the following steps (see graphic below):

Log on

... Source code

* Call BAPI

Source code

* Call BAPI

Source code

Call BAPI BapiService.TransactionCommit()

... Source code

* Call BAPI

Source code

* Call BAPI

…. Source code

Call BAPI BapiService.TransactionCommit()

... Source code

Log off

BAPI Programming SAP AG

BAPI Transaction Model Without Commit

64 December 1999

BAPI Transaction Model Without Commit

R/3(ABAP). . .

Visual Basic. . .

BAPIcall

. . .

BAPIcall

. . .

BAPIService Transaction Commit call

. . .

Log onLogical

Unit of Work

Commit Work

Log off

RFC Session

The same rules apply in this model as in the BAPI Transaction Model With Commit [Page 60].

But also keep in mind:

•••• If a termination message is displayed (message type A) in the Return parameter, a databaserollback can be executed by the BAPI. This causes all the activities carried out since the lastCOMMIT WORK command to be canceled. This situation must be described in the Returnparameter documentation for the BAPI in question.

•••• Operations that change the database must be carried out through the updating process.

SAP AG BAPI Programming

Customer Enhancement Concept for BAPIs

December 1999 65

Customer Enhancement Concept for BAPIsUseThe customer enhancement concept for BAPIs enables customers to enhance business objecttypes without modifications, for example, make table enhancements to master data, and then toreflect these enhancements in the BAPIs of the business object types.

The customer concept described here has been introduced in Release 4.5B.Customer exits implemented using the enhancement concept valid before do nothave to be reprogrammed.

The customer enhancement concept is converted in the BAP interface by standardized extensionparameters which can be combined with one or both of the enhancement mechanisms below:

•••• By the BAPI table extensions developed by BAPI programmers. Customers must notprogram these extensions.

•••• Conventional customer exits that can be individually implemented.

The customer enhancement concept is not intended for developing individual industry solutionswithin SAP; a special enhancement concept has been defined for industry solutions. For furtherinformation contact the BAPI Development.

FeaturesExtension Parameters in BAPI InterfacesFirst consider which tables used by the BAPI may be suitable for customer enhancements. Then,depending on the requirements of the BAPI, create, one extension parameter for the data importand/or one extension parameter for the data export.

Note the following guidelines:

•••• The naming convention for the extension parameter is ExtensionIn for import parameterenhancements and ExtensionOut for export parameter enhancements.

•••• Define the extension parameter as a table parameter.

•••• Use the reference structure BAPIPAREX for extension parameters. With this structure theextension parameter can be used as a generic data container.

Extension parameters can relate to BAPI table extensions and/or to customer exits already in theprogram (see below).

We recommend you use BAPI table extensions, if possible, because customer enhancementscan be automatically used by the BAPI and do not require customers to rewrite any programs.You should create customer exits to enable customers to enhance BAPI interfaces in situationswhere it was not anticipated enhancements may be needed.

BAPI Table ExtensionsBAPI table extensions and help structures are used to copy data from a customer table extensionand to place it in an extension parameter. Customer-defined data can then be read andprocessed by the BAPI automatically.

BAPI Programming SAP AG

Customer Enhancement Concept for BAPIs

66 December 1999

BAPI table extensions can only refer to tables whose contents belong to the business objecttype. For example, the Create() BAPI of the business object type Material, cannot have a BAPItable extension that supports a table extension of the business object type Equipment.

The graphic below shows how extension parameters and BAPI table extensions functiontogether:

The BAPI TravelAgency.CreateFromData has a standardized parameter ExtensionIn forextending the import parameter to be read.

The parameter ExtensionIn relates to the BAPI table extension BAPI_TE_STRAVELAG. Thisconsists of:

•••• A key part predefined by SAP (AGENCYNUM). The key field of the database tableSTRAVELAG which the BAPI table extension refers to.

•••• Data part (CUSTOMER FIELD1 to CUSTOMER FIELD3) determined by the customer in anappend technique . These are the fields with which the customer extended tableSTRAVELAG.

BAPI: TravelAgency.CreateFromData

Parameter: AgencyDataIn

AgencyNumber

Return

ExtensionIn

Fields from ExtensionIn:

BAPI Table Extension: BAPI_TE_STRAVELAG

Database table: STRAVELAG

Key field AGENCYNUMFields NAME

STREET......TELEPHONEURLLANGU.APPENDCUSTOMER FIELD _1CUSTOMER FIELD _2CUSTOMER FIELD _3

Structure Valuepart1 Valuepart2

AGENCYNUMFelder.APPENDCUSTOMER FIELD _1CUSTOMER FIELD _2CUSTOMER FIELD _3

BAPI_TE_STRAVELAG

Valuepart3 Valuepart4

Values from CUSTOMER FIELD_1,CUSTOMER FIELD _2, CUSTOMERFIELD _3

Customer-defined fields are able to be automatically processed because the use of BAPI tableextensions are searched for in the ExtensionIn parameter in the BAPI program code. The nameof the active BAPI table extension (here BAPI_TE_STRAVELAG) is inserted in the STRUCTUREfield of the ExtensionIn parameter. The key of the extended table (AGENCYNUM) and thecustomer-defined data part (CUSTOMER FIELD1 to CUSTOMER FIELD3) are transferred to thedata fields VALUEPART1 to VALUEPART4 in the extension parameter. If the fields inserted by acustomer in a BAPI table extension exactly match the fields in the table extended by thecustomer, the BAPI can read or write the data using 'move-corresponding'.

As shown by the arrows and color in the graphic, specific guidelines and naming conventionsmust be followed for the implementation and when using extension parameters with BAPI tableextensions, to assure that customer data can be processed without errors occurring.

When creating BAPI table extensions, make sure you:

SAP AG BAPI Programming

Customer Enhancement Concept for BAPIs

December 1999 67

•••• Create one BAPI table extension for each table to be extended.

•••• The naming convention for BAPI table extensions is BAPI_TE_<Table name>.

The BAPI table extension BAPI_TE_MARA relates to table MARA.

•••• The structure of the BAPI table extension must contain the key fields of the table that theBAPI table extension relates to.

The BAPI table extension BAPI_TE_MARA has a field MATNR, as MATNR is thekey field of table MARA.

•••• Customers can use only fields of data type CHAR and similar data types in BAPI tableextensions. This restriction is due to the reference structure BAPIPAREX of the extensionparamters. Customers cannot use fields from the standard table in the append of the BAPItable extension because a 'move corresponding' would overwrite the SAP field. For furtherinformation see the Customer Enhancement Concept [Ext.] in the BAPI User Guide.

•••• A BAPI table extension can have a maximum length of 960 characters.

•••• All available BAPI table extensions must be listed in the documentation on the extensionparameter.

Programming examples are provided in the function modulesBAPI_TRAVELAGENCY_CREATE and BAPI_TRAVELAGENCY_GETDETAIL. Themethods are called TravelAgency.CreateFromData() and TravelAgency.GetDetail().

The extract below from the program code for the BAPITravelAgency.CreateFromData shows how the ExtensionIn parameter and the BAPItable extension are used.loop at extensionin.

case extensionin-structure.

when 'BAPI_TE_STRAVELAG'.

move extensionin+c_lenstruc to wa_bapi_te_stravelag.

move agencynumber to wa_bapi_te_stravelag-agencynum.

read table t_stravelag with key agencynum =agencynumber.

catch system-exceptions conversion_errors = 1.

move-corresponding wa_bapi_te_stravelag tot_stravelag.

endcatch.

BAPI Programming SAP AG

Customer Enhancement Concept for BAPIs

68 December 1999

Customer ExitsIf BAPI table extensions cannot be used, you should insert customer exits in suitable places inthe source code of the BAPI, to enable customers to program their own exits and to include themin the BAPI.

The standard rules for customer exits apply and maintenance with Transaction SMOD (SAPinternal) and CMOD (for customers). For further information see the documentation on SAPEnhancement Management (for Transaction SMOD) and in BC - Enhancing the SAP Standard[Ext.] (for Transaction CMOD).

Note the following:

•••• BAPIs that cause database changes, e.g. Create(), Change()

Create a customer exit that checks all the data and transfers data to internal, customer-defined structures.

A second customer exit must be provided for writing data to customer-defined tables.

•••• BAPIs with read function, for example GetDetail()

Create a customer exit after the SAP data retrieval to enable customers to then importtheir own data.

SAP AG BAPI Programming

Internal and External Data Formats

December 1999 69

Internal and External Data FormatsUseBAPIs are not end user interfaces, they are programming interfaces that can be used in diverseapplication areas, for instance, to connect non-SAP systems and PC products to the R/3 System.To meet the requirements of this diverse range of applications, a common strategy forrepresenting data in the BAPI interface must be used.

General GuidelinesFields in BAPI parameters must be presented in the internal form used in the database and not ina form formatted in the BAPI interface. Because of the reasons above, BAPIs should not convertdata between the internal and external data formats, except in the circumstances outlined below.

For example, the date in a BAPI must be in the format used internally, YYYYMMDD, whereYYYY is the year, MM the month and DD the day.

The graphic below shows the BAPI programming interface where data is transferred at thesource code level and not at the application interface level.

BAPI Programming Interface

Applicationprogram

Applicationprogram

GUIGUI

BAPI

External data format, for example, on the screen (GUI)

Internal data format

ExceptionsThere are exceptions where the calling program has to map and convert the data between theinternal and external data formats in a BAPI.

BAPI Programming SAP AG

BAPI Programming Interface

70 December 1999

For these exceptions you can generate function modules that can map and, if required, convertbetween the internal and external data formats. The section Converting Between Internal andExternal Data Formats [Page 140] describes how to generate these function modules. You canuse these function modules in the source code of your BAPI for the following:

•••• To map the internal work structures to the external BAPI structures before calling the BAPI

•••• To map the result to the internal work structure after the BAPI has been called

•••• To map the imported parameters to the internal structures (import parameter structures)when you are implementing the BAPI

•••• To map the result from the internal structure to the BAPI (export parameter structures) whenyou are implementing the BAPI

These exceptions are:

•••• Currency amount fields

In an R/3 System a currency amount field can only be used when accompanied by acurrency code. Only then can the decimal point be set correctly. A currency code fieldmust be assigned to each currency amount field. For example, two yen are stored as0.02 in the field of data type CURR in the database. Non-SAP systems will notunderstand this syntax.

All R/3 currency data types have two digits after the decimal point, even thoughcurrencies do exist with three digits after the decimal point.

For these reasons, the data type CURR cannot be used in the BAPI interface. Adhere tothe following guidelines when using currency amount fields in BAPIs:

− You must not use parameters and fields of data type CURR in the interface

− All parameters and fields for currency amounts must use the domain BAPICURRwith the data element BAPICURR_D or BAPICUREXT with the data elementBAPICUREXT.

− The position of the decimal point in currency amount fields must be convertedcorrectly

You can use two function modules for this conversion. The function moduleBAPI_CURRENCY_CONV_TO_EXTERNAL converts currency amounts from R/3internal data formats into external data formats. The function moduleBAPI_CURRENCY_CONV_TO_INTERNAL converts currency amounts fromexternal data formats into internal data formats.

•••• Quantity Fields and Unit of Measurement FieldsLike currency amount fields, the decimal point in quantity fields and unit of measurementfields must be converted correctly.

A field to indicate the amount or the unit of measure must be assigned to all amount andquantity fields.

Quantity fields have no standard domain that can be used for BAPI structures.

•••• Internal keysIn some situations an internal technical key is maintained in the database alongside theexternal key. Examples are work breakdown structure plans or networks in projectsystems.

SAP AG BAPI Programming

BAPI Programming Interface

December 1999 71

You must always use the external key in the BAPI interface.

To convert activity codes in networks, the following function modules are provided:

− EXT_ACTIVITY_GET_INT_ACTIVITY, to convert from the external activity into theinternal activity

− INT_ACTIVITY_GET_EXT_ACTIVITY, to convert from the internal activity into theexternal activity.

These conversion transactions are not included in the transactions described in thesection Converting Between Internal and External Data Formats [Page 140].

•••• ISO codesIn R/3 Systems ISO codes are currently supported for language, country, currency, andunit of measure fields.

If you use one or more of these fields in your BAPI you have to make two fields availablefor each of these fields in the BAPI interface: one field containing the SAP code andanother containing its corresponding ISO code. Use the naming convention,Fieldname_for_SAPCode_ISO for the field containing the ISO code.

For example, the field LANGU contains the country codes used internally in R/3, forinstance E. The corresponding field for the ISO code would then be named LANGU_ISOand would contain the corresponding ISO code EN.

Implement the BAPI as follows:

− When you export data from the BAPI both fields must contain corresponding values.

− When you import data into the BAPI the ISO code is only significant if no value wasgiven in the SAP code.

Use the domains below for the ISO codes:

Domains for SAP internal codes and ISO codes

Size ISO Code Domain SAP Code Domain

Currency key ISOCD WAERS

Quantity unit ISOCD_UNIT MEINS

Language key LAISO SPRAS

Country key INTCA LAND1

For every domain there is a data element of the same name.

•••• Dates and TimeIn accordance with ISO standard 8601 dates an time must be transferred between twoexternal systems in Universal Coordinated Time (UTC). UTC is the equivalent of theformerly used term GMT (Greenwich Mean Time) and is now used as the unique timereference across the globe.

In the BAPI interface you have to provide a field for the time zone, that is, the location ofan object with respect to its local time, as well as a field for the UTC time stamp. Youcan also specify the local time.

The naming convention for the UTC time stamp field is <Field name for time zone>_ISO.

BAPI Programming SAP AG

BAPI Programming Interface

72 December 1999

The following types are provided for dates and time.

− TIMESTAMP

− TIMEZONE

•••• Specific fields in address structuresThese fields are:

• Address text (fields TITLE_P, TITLE and FORMOFADDRESS)

• Academic title (fields TITLE_ACA1 and TITLE_ACA2)

• Name prefixes, for example "von", "van der" (fields PREFIX1 and PREFIX2)

• Names affixes, for example, titles (field TITLE_SPPL)

For more information see Address Parameters [Page 123].

BAPIs for Converting Between Internal and External Data Formats(Converting Domains)BAPIs are programming interfaces in which, with a few exceptions, only the internal data formatshould be used. However, application programmers calling a BAPI from within their program maysometimes require the external format, for example, to display data on the screen. In such casesthe calling program must be able to convert between the internal and external data formats.

The calling program can use conversion BAPIs to convert data into the required format: Theseare described in the BAPI User Guide in the section Service BAPIs for General BAPI Functions[Ext.].

SAP AG BAPI Programming

Providing Input Help (F4 Help)

December 1999 73

Providing Input Help (F4 Help)

UseUsers of R/3 Systems can use the F4 key to retrieve information about the possible input valuesfor screen fields.

Information about the possible values for a field should also be available to those users who areworking with the data in the R/3 System from an external program, via BAPI calls. For example,the user of a Visual Basic program which incorporates a BAPI to display or modify data in R/3should have transparent access to the functionality of the F4 input help.

FeaturesIn order to provide input help, a calling program can use the BAPI HelpValues.GetList(). Thismethod is based on the RFC-enabled function module BAPI_HELPVALUES_GET, which obtainsthe possible input values for a field that is passed in a BAPI call. Detailed information about thestructure and use of the BAPI HelpValues.GetList() is available in the documentation for thisBAPI.

The BAPI HelpValues.GetList() method refers to the help view for the check table, matchcodes ordomain fixed values linked to the field in the ABAP Dictionary.

For this reason, you have to create or specify relevant check tables, match codes or domain fixedvalues. Only then can the calling program access the relevant input values for your BAPI fieldsusing the BAPI HelpValues.GetList().

As of Release 4.5A you have to specify a foreign key, if a check table has beendefined in the domain. Otherwise F4 input help cannot be displayed.

For information about check tables, matchcodes and domain fixed values see the ABAPDictionary [Ext.].

Authorization CheckIn some cases you will only want to allow only those persons with a specific user profile toaccess information in F4 input help. To do this you can carry out authorization checks within theBAPI using table BAPIF4T.

This table comprises the following fields which you have to fill with the values for your BAPI.

• OBJTYPE (object type)

The technical name of the SAP business object type, for example, BUS1065.

• METHOD (verb)

The name of a BAPI for the business object type named above, for example, GetList.

• DTEL (data element)

The name of a data element for which a possible entry is specified. For example, anelementary input help could be specified for the data element PERNR_D and beprotected from unauthorized access.

BAPI Programming SAP AG

Use

74 December 1999

• FNAM (name of the function module)

The name of the function module that you have to create and that carries out theauthorization check for the data element. This function module must have the followingpredefined interface:*"-------------------------------------------------------*"*"Local interface:*" IMPORTING*" VALUE(OBJTYPE) LIKE BAPIF4F-OBJTYPE*" VALUE(METHOD) LIKE BAPIF4F-METHOD*" VALUE(DTEL) LIKE BAPIF4F-DTEL*" VALUE(SHLPNAME) LIKE BAPIF4F-SHLPNAME*" VALUE(TABNAME) LIKE BAPIF4F-TABNAME*" EXPORTING*" VALUE(RETURN) LIKE BAPIF4F-RETURN*"---------------------------------------------------------

As the template for your function module you can use the function moduleBF_BAPI_F4_AUTHORITY which provides exactly this interface. Copy this functionmodule and follow the documentation provided with it.

The additional parameter SHLPNAME contained in the function module interfaceprovides the name of the active input help for the table or for the data element. Theparameter TABNAME contains the name of the value table.

The return code of the parameter RETURN is:

− 'X' if the user of the BAPI is not authorized to call up the valid input values for a field.

− ' ' (no value), if the user of the BAPI is authorized to display the input values for afield.

During runtime the function module is called dynamically by the BAPIHelpValues.GetList().

An authorization check can be carried out at business object type, method or data elementlevel:

To carry out authorization check atthis level.......

... ......the following fields in table BAPIF4Tmust be filled.

Business object type OBJTYPE, FNAMBAPI OBJTYPE, METHOD, FNAMData Element OBJTYPE, METHOD, DTEL, FNAM

SAP AG BAPI Programming

Providing Interface Descriptions

December 1999 75

Providing Interface DescriptionsUseDescriptive text, for example, short texts and texts on how to write help functions are very usefulfor using BAPI interfaces.

Various functions are provided that support R/3 users in carrying out the tasks required of them.For example, F1 help provides information on specific input fields.

F1 help should also be available to users who are working with data in an R/3 System from anexternal program, via BAPI calls.

FeaturesService BAPIs are provided that are used by external programs to call documentation anddescriptions of BAPI interfaces.

•••• BapiService.FieldHelpGetDocu()

This method reads the documentation (F1 help) for the fields in a BAPI parameter.Application developers can use this method to provide end-users with descriptions offields in a BAPI parameter.

To ensure that F1 help for your BAPI can be called via the methodBapiService.FieldHelpGetDocu(), data element documentation must be written for eachparameter field in the BAPI.

•••• BapiService.InterfaceGetDocu()

This method reads the whole interface documentation for a BAPI. You can use thismethod to access the documentation on the business object type, method, parametersand parameter fields.

To support application developers with their work, the documentation on BAPI interfacesmust be complete. For internal use SAP provides detailed guidelines on writing BAPIdocumentation. You can get a copy of the guidelines from your contact person in theBAPI Development group.

See the general Documentation Guidelines [Page 88].

•••• BapiService.MessageGetDetail()

This method returns the short and long texts of BAPI error messages.

To enable application developers to process BAPI error messages, you have to maintainthe short and long error texts for the BAPI. You should follow the standard ABAPprogramming rules.

For information about these BAPIs see the relevant BAPI documentation.

BAPI Programming SAP AG

Providing Interface Descriptions

76 December 1999

SAP AG BAPI Programming

Buffering with Write BAPIs

December 1999 77

Buffering with Write BAPIsUseTo save external systems each having to define their own data, predefined buffering mechanismsshould be implemented in all write BAPIs (i.e. BAPIs that create and change data).

For SAP internal use this is particularly relevant for BAPIs developed as of Release 4.6A. If youwant to implement a buffer for BAPIs in an earlier release, you should first contact a colleague inthe central BAPI development group.

For BAPIs standard R/3 System mechanisms can be used to buffer application data. Data to becreated or changed by a BAPI is not created in the update buffer, it is first collected in the globalbuffer of the BAPI function module group. Then the whole buffer is updated at a specified time.

This has the following advantages:

•••• Improvement in performance of the whole system.

The updating of individual operations is delayed and they can all be updated together.Techniques such as "array insert" improve system performance. If buffering is not used,each change must be updated separately.

•••• Several changes to an application instance

With the first change the data is read from the database into the buffer and the change ismade in the buffer. With the next change, the system recognizes that the data alreadyexists in the buffer and also makes the change in the buffer. If buffering is not used, thefirst change would have to be updated before a second change could be made.

•••• Using in Application Link Enabling

BAPIs with buffering are especially suited in situations where mass data is exchangedbetween systems via Application Link Enabling (ALE).

The buffering mechanism enables application instances to be processed separately inthe ALE layer, while still enabling the instances to be updated together. Unlike multipleBAPIs, such as, SaveReplicaMultiple(), this procedure allows error handling of individualinstances.

BAPIs with buffering mean that there is no need to use or implement multiple BAPIs.

IntegrationThe Transaction Model for BAPIs Without Commit [Page 63] in use since Release 4.0 can beenhanced on the basis of these advantages:

•••• Within one Logical Unit of Work (LUW) several changes or detailed changes can be carriedout for one instance.

•••• All changes (to one or more instances) are updated together by the BAPIBapiService.TransactionCommit().

This graphic shows the transaction model for BAPIs without buffering:

BAPI Programming SAP AG

Buffering with Write BAPIs

78 December 1999

Transaction Model Without Buffering

Client(e.g. VisualBasic)

Server (R/3)

Create i1Create i2

BapiService.TransactionCommit

Change i1 BapiService.TransactionCommit

i1 is passed to pdate

Updateperformed:i1 and i2 are

updated separately

i2 passedto update

Updateperformed:i1 updated

i1 passedto update

LUW LUW

SAP AG BAPI Programming

Buffering with Write BAPIs

December 1999 79

This graphic shows the transaction model for BAPIs with buffering:

Transaction Model with Buffering

Client(z.B. VisualBasic)

Server (R/3)

Create i1Create i2

Change i1BapiService.TransactionCommit

Instances arecreated and processed

in the buffer

Buffer contents passed toupdate. Update is

performed: i1 and i2 are updated together

LUW

PrerequisitesThe buffering mechanism for BAPIs must be implicit, that is, the caller must not have to controlthe buffering. A calling program must be able to use, for example, a Create()or Change() BAPIwith buffering as well as it can use a BAPI without buffering. The buffer is updated implicitly inR/3.

If buffering has been implemented for a business object type, all write BAPIs of this businessobject type must also be implemented with buffering.

If write BAPIs with buffering have been implemented for a business object type, this affects theread BAPIs of this object type. Refer to the information in the Activities section below.

FeaturesFor BAPIs with buffering, in addition to the standard guidelines, the following implementationsteps and characteristics described below are required.

Function Modules for Updating the Contents of the BufferAs BAPIs with buffering can only create or change instances in the buffer, you have to provideone or more function modules to carry out the final update of the buffer contents. These updatemodules transfer the entire contents of the buffer to the update program.

These function modules should not be implemented as BAPIs, as these are only used in thesystem in which the buffer is also used.

BAPI Programming SAP AG

Buffering with Write BAPIs

80 December 1999

The naming convention for these function modules is:<Business object name>_SAVEBUFFER.

Exceptions must not be defined for the update modules, as these are not run until the end of theprogram, when error handling is no longer possible (see Special Characteristics below).

Function Modules for Deleting the Contents of the BufferTo ensure that the buffer is empty at the start of a transaction, you must provide a functionmodule that deletes the contents of the buffer. This delete function module deletes the entirecontents of the buffer and removes any locks on the instances. Neither should you implementthis function module as a BAPI, because it is only used in the system in which the buffer is alsoused.

The naming convention for this function module is:<Business object name>_CLEARBUFFER.

No exceptions can be defined for delete modules because these are not run until the end of thetransaction, when error handling is no longer possible (see Special Characteristics below).

Special CharacteristicsBAPIs with buffering need to have special characteristics. For example, these BAPIs must beable to deal with errors because a caller cannot reprocess data in the buffer. As data is bufferedimplicitly, no administration BAPIs are provided for callers.

Consistency of the Buffer ContentsA BAPI with buffering must carry out all the processing steps, except for updating. Theconsistency of all instances created or changed in the buffer must be guaranteed by theapplication.

This means that:

•••• Only operations that can be updated with consistency guaranteed can be carried out in thebuffer. The update module itself cannot perform consistency checks.

•••• All other steps required before updating, such as assigning numbers or creating applicationblocks, must be carried out before calling the update module.

•••• For operations that cannot be updated consistently, no action can take place. In these casesthe error situation must be reported in the BAPI return parameter.

Calling Update ModulesAfter the buffer operations have been successfully carried out, using the command

PERFORM <routine> ON COMMIT

call a form routine <routine> which then calls the update module(s).

The update modules must be called using the command

CALL <Business object name>_SAVEBUFFER IN UPDATE TASK

to flag the execution in the update program.

By adding 'ON COMMIT' to the command PERFORM <routine> ON COMMIT, updating is notcarried out immediately,it is carried out in the next COMMIT WORK. This way any number ofBAPI calls can be collected together. The final COMMIT WORK command that is executed viathe BAPI BapiService.TransactionCommit(), executes the form routine and also each update

SAP AG BAPI Programming

Buffering with Write BAPIs

December 1999 81

module once only. For this reason error handling cannot be performed in this form routine nor inthe function module.

Subscribing the Delete ModuleAt the start of each LUW the buffer must be empty. Any instances that may exist in the buffer,which were updated in an earlier LUW, are no longer blocked and may be older than the versionsin the database. If this instance is updated again, inconsistencies would result.

At the end of each LUW, the buffer contents must be deleted by calling the delete module. Thiscan only be done by the BAPIs BapiService.TransactionCommit() andBapiService.TransactionRollback(). To supply these BAPIs with the necesary information, BAPIswith buffering must subscribe thier delete module for the BAPI BapiService.TransactionCommit()bzw. BapiService.TransactionRollback().

The delete module is subscribed by calling the central function moduleBUFFER_SUBSCRIBE_FOR_REFRESH, whereby the parameter NAME_OF_DELETEFUNCmust contain the name of the delete module.

No COMMIT WORK or ROLLBACK WORK CommandBAPIs with buffering must not execute COMMIT WORK or ROLLBACK WORK commands.

DocumentationEach BAPI with buffering must be explicitly documented as such.

Activities

Keep in mind the following important information about how write BAPIs withbuffering interact with read BAPIs of the same business object.

Write BAPIs with Buffering and Read BAPIs for the Same Business ObjectNo Buffering for Read BAPIsIf write BAPIs with buffering are implemented for the same business object type, read BAPIs arenot allowed to use the buffer for the same business object type, so that data read from thedatabase can be stored, thereby avoiding further database accesses.

As the imported data is not locked, the corresponding data in the buffer would become outdatedover time. Subsequent read operations would first access the buffer and read the potentially out-of-date data, as data in the database can only be read, if this data is not in the buffer.

Buffer Instances Are "Real" InstancesAll instances created or changed by write BAPIs in the buffer are consistent. They can be usedby other change BAPIs for further processing within the same LUW.

To guarantee the consistent behavior, all read BAPIs must handle existing instances that are inthe buffer, and not yet in the database, as valid instances. Read BAPIs must be implemented insuch a way that they first try to read an instance in the buffer and only start searching thedatabase, if the instance is not found in the buffer.

A buffer instance is therefore "real" instance. For example, a BAPI ExistenceCheck() mustsearch for the existience of an instance in the buffer also.

BAPI Programming SAP AG

82 December 1999

Documenting Read BAPIsEach read BAPI that handles the buffering of corresponding write methods must be documented.

SAP AG BAPI Programming

Example of Implementation and Process Flow

December 1999 83

Example of Implementation and Process FlowThe example below describes the implementation and process flow of BAPIs with buffering.

A more detailed example is the BOR is the BAPI CreateFromData() of business object typeTravelAgency (SAGENCY. The development class is SAPBC_BOR.

ImplementationFor the business object <object>, BAPIs with buffering should be provided, in particular Create()and Change() BAPIs. In the BAPI function group <object>, belonging to the business object, thefollowing routines or function modules are created.

•••• Form routine for the updateform <buffersave>.

call <object>_savebuffer in update task.

endform.

•••• Update modulefunction <object>_savebuffer.

...

{Read buffer}

{Update buffer}

...

endfunction.

•••• Delete modulefunction <object>_clearbuffer.

...

{Update buffer}

...

endfunction.

•••• Function module for the Create() BAPIfunction bapi_<object>_create.

call buffer_subscribe_for_refresh

exporting

name_of_deletefunc = <object>_clearbuffer.

{Operations in buffer}

perform <buffersave> on commit.

endfunction.

•••• Function module for the Change() BAPI

BAPI Programming SAP AG

Example of Implementation and Process Flow

84 December 1999

function bapi_<object>_change.

call buffer_subscribe_for_refresh

exporting

name_of_deletefunc = <object>_clearbuffer.

{Operations in buffer}

perform <buffersave> on commit.

endfunction.

Process FlowAn external application executes the BAPI Create() of business object <object> twice, to createthe two instances 4711 and 4712. Then another change is made to instance 4711 using the BAPIChange(). To complete the LUW, the BAPI BapiService.TransactionCommit() is executed. Thesteps are:

Step Process Flow

The delete module <object>_clearbuffer is subscribed by callingbuffer_subscribe_for_refresh for the BAPI BapiService.TransactionCommit().

The buffer is empty. Instance 4711 is created in the buffer.

1.Callmethod<object>.Create() forinstance4711

The call of the update module is <object>_savebuffer is flagged using the form routine<buffersave>.

The delete module <object>_clearbuffer is subscribed by calling thebuffer_subscribe_for_refresh for BAPI BapiService.TransactionCommit(). As this isalready subscribed, it is not subscribed again.

Instance 4712 does not yet exist in the buffer; it is created here.

2.Callmethod<object>.Create() forinstance4712

The call of the update module is <object>_savebuffer is flagged using the form routine<buffersave>. As this is already flagged, it is not flagged again.

The delete module <object>_clearbuffer is subscribed by calling the bufferbuffer_subscribe_for_refresh for BAPI BapiService.TransactionCommit(). As this isalready subscribed, it is not subscribed again.

3.Callmethod<object.>Change()forinstance4711

Instance 4711 exists in the buffer; it is changed here.

SAP AG BAPI Programming

Example of Implementation and Process Flow

December 1999 85

The call of the update module is <object>_savebuffer is flagged using the form routine<buffersave>. As this is already flagged, it is not flagged again.

The form routine <buffersave> of the function group <object> is executed once only bythe COMMIT WORK command. This executes the update module and the contents ofthe buffer is transferred to the update program.

4.CallmethodBapiService.TransactionCommit()

After the COMMIT WORK command, the delete modules subscribed for the BAPIBapiService.TransactionCommit() are called, that is, the function module<object>_clearbuffer is executed and the buffer for the business object <object> isemptied.

BAPI Programming SAP AG

Improving Performance

86 December 1999

Improving PerformanceUseIn order to improve the performance of your BAPI, you should follow the standard ABAPprogramming guidelines:

•••• Use only complete WHERE conditions to minimize the amount of data to be transferred.

•••• Avoid unnecessary database access.

•••• Do use of arrays.

•••• Buffer data, for example in the local memory of the function module. Note that you must notbuffer data in the global memory.

•••• The locking granularity must correspond to the instance granularity in the object model.

•••• Do not generate programs at runtime.

See the internal SAPnet for further notes about effective programming in the R/3 environment.

Additional Guidelines for BAPI ProgrammingThe function module on which a BAPI is based can be accessed by external programs usingRFC. For this reason, you should follow these additional guidelines when programming BAPIs:

•••• Large amounts of data

Mass data is treated differently in ABAP programs, which use the SAPgui (graphical userinterface) as a front end, and in programs developed on external development platformssuch as Visual Basic.

If large amounts of data are read in the R/3 System, for example a list containing manyentries, the majority of the data remains on the application server. Only the data that isactually displayed is sent to the front end. In contrast, if you are programming with VisualBasic, all the data will be sent from the application server to the client system. Thisincreases the load on the network and the amount of memory required in the clientsystem.

You need to cover the situation when your BAPI has to read mass data. For example,you could specify a limit so that only the first n data records are read. Alternatively yourBAPI could return a message to the calling program indicating that the amount of datahas exceeded a certain limit and that a new selection should be made.

•••• Do not define parallel processes.

•••• If no COMMIT WORK is triggered after a BAPI is called, a lock that has been set has to beexplicitly deleted.

•••• To reduce the duration of database locks, you should not assign numbers to themindividually. Instead make use of the buffers. Read the numbers to a buffer and assign thenumbers directly from the buffer.

•••• Lock periods can be minimized by making database updates as close as possible to theCOMMIT WORK command. This reduces the duration of database locks and the risk ofblocking other processes.

SAP AG BAPI Programming

Improving Performance

December 1999 87

•••• The less specific the (partial) key of a modified data record is, the more likely it is that thedata record will be accessed by multiple BAPIs, causing the record to be locked. Forexample, running a statistic on plant level will have a negative impact on the performance ofthe BAPI, whereas a statistic based on plant and material will cause fewer locks because itwill apply to fewer BAPIs.

•••• Minimize the use of read transactions which depend on a previous database COMMIT(committed read). These read transactions have to wait for the COMMIT WORK command ofthe update transaction to be processed.

•••• All tables that are not protected by SAP internal locks must always be updated in the sameorder to prevent a deadlock.

BAPI Programming SAP AG

Documentation Guidelines

88 December 1999

Documentation GuidelinesPurposeTo use a BAPI in an application program, application developers need to know:

•••• Which BAPI provides the required data, that is, they need to know what the BAPI can do.

•••• How the BAPI is called, that is what are the parameters and fields of the BAPI interface.

Application developers access the technical meta data and documentation of BAPIs from theBusiness Object Repository.

This section contains general guidelines for documenting BAPIs. For internal use, SAP providesdetailed guidelines on writing BAPI documentation. You can get a copy of the guidelines fromyour contact person in the BAPI Development group.

PrerequisitesBAPIs are business interfaces to the R/3 System and users are not required to have a thoroughknowledge of the R/3 System and the R/3 development environment.

Readers of BAPI documentation are often not R/3 experts or business application experts.

Process FlowTo give application developers a complete picture of the functionality of a BAPI, the followingdocumentation must be provided:

Documentation on MethodsCreate this documentation in the Function Builder in the function module that the BAPI is basedon. The purpose of this documentation is to explain what the method does and how thecommunication with external programs works. The documentation should help customers decidewhether a method is appropriate to perform the task in question and it should therefore provideanswers to the following questions:

•••• What is the business function of the BAPI and what can it be used for?

•••• What exactly are the functions of the BAPI?

•••• Are there any important limitations, that is, functions that this BAPI cannot perform?

•••• What must you pay particular attention to with this BAPI? For example, is specialauthorization required to use this BAPI?

•••• Are there any Customizing dependencies?

•••• What dependencies are there between this BAPI and other BAPIs, and between individualmethod parameters?

If the BAPI uses a COMMIT WORK command or works with buffering, you must include this inthe documentation.

SAP AG BAPI Programming

Documentation Guidelines

December 1999 89

Documentation on Method ParametersDocumentation on the individual parameters is also written in the Function Builder in theassociated function module. Parameter documentation should provide answers to the followingquestions:

•••• What is the parameter used for?

•••• Which fields must be filled, that is, what are the mandatory fields?

•••• What are the dependencies between fields?

•••• Are there any fixed values and what do they do?

•••• What are the default values of the parameter? All the fields that are assigned default valuesby Customizing and are therefore write-protected, must be documented.

•••• Which return codes may be returned to the calling program directly or indirectly in the Returnparameter?

Data Element Documentation on Parameter FieldsA calling program can call data element documentation (F1 help) for a field in a BAPI parameterusing the Service BAPI BapiService.FieldHelpGetDocu (see Providing Input Help [Page 73]).

For this reason you have to write data element documentation for each field in BAPI parameters.

Further DocumentationTo provide the complete context of a BAPI, the information below must also be available:

•••• Documentation on the business object type the BAPI is implemented for.

•••• Documentation on the key fields of the business object type.

BAPI Programming SAP AG

Programming Standardized BAPIs

90 December 1999

Programming Standardized BAPIsPurposeSome BAPIs and methods provide basic functions and can be used for most SAP businessobject types. These BAPIs are called “standardized” BAPIs.

Process FlowIf your BAPI is a standardized BAPI, you should implement it following the programmingguidelines described in the following sections.

SAP AG BAPI Programming

Programming GetList() BAPIs

December 1999 91

Programming GetList() BAPIsUseWith the BAPI GetList() you can select a range of object key values, for example, companycodes and material numbers. The key values returned by this BAPI can be passed on to anotherBAPI for further processing, for example, the BAPI GetDetail().

The BAPIs GetList() is a class method (instance-independent).

FeaturesProvide all the relevant fields in the interface of the GetList() BAPI. How complex and extensiveyou structure the interface, depends on the requirements the BAPI is to fulfill.

Import ParametersThe interface of a GetList() BAPI must provide selection parameters, in which the requiredselection criteria can be passed on by the calling program. The structure of selection parametersis described in the section Selection Parameters [Page 134].

You must also create the parameter MaxRows that enabes you to limit the number of entriesselected. This parameter prevents too large a value set from being selected, if the selectionparameter specification is not very precise. Use the data element BAPIMAXROW as thereference type for the MaxRows parameter.

Export ParametersThe key values selected by the BAPI GetList() are returned to the calling program in a table,together with other useful information, for example, short texts.

To report messages from the method call back to the calling program, you should create theexport parameter RETURN. For more information about this parameter see Return Parameters(Error Handling) [Page 130].

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

BAPI Programming SAP AG

Example of a GetList() BAPI

92 December 1999

Example of a GetList() BAPIThe BAPI GetList of the business object type CostCenter (BUS0012) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Programming GetDetail() BAPIs

December 1999 93

Programming GetDetail() BAPIsUseThe BAPI GetDetail() is used to read details of specific object instances.

The BAPI GetDetail() is an instance method.

FeaturesImport ParametersThe import parameters of the GetDetail() BAPI must contain the key fields of the business objecttype.

For the associated method definition in the BOR, the key fields must not also be specified asmethod parameters. For this reason, the BOR/BAPI Wizard does not include the function moduleparameters for the key fields in the method definition, when it creates a BAPI.

Export ParametersThe export parameters of a BAPI contain details of the instance. According to the amount ofinformation, this should be structured in several parameters with meaningful names.

To report messages from the method call back to the calling program, you should create theexport parameter Return. For more information about this parameter see Return Parameters(Error Handling) [Page 130].

Extension ParametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

BAPI Programming SAP AG

Example of a GetDetail() BAPI

94 December 1999

Example of a GetDetail() BAPIThe BAPI GetDetail() of the business object type CompanyCode (BUS0002) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Example of a GetDetail() BAPI

December 1999 95

BAPI Programming SAP AG

Programming GetStatus() BAPIs

96 December 1999

Programming GetStatus() BAPIsUseWith the BAPI GetStatus() you can retrieve information about the status of a particular objectinstance.

The BAPI GetStatus() is an instance method.

FeaturesImport ParametersThe import parameters of the GetStatus() BAPI must contain the key fields of the business objecttype.

For the associated method definition in the BOR, the key fields must not also be specified asparameters. For this reason, the BOR/BAPI Wizard does not include the function moduleparameters for the key fields in the method definition, when it creates a BAPI.

Export ParametersThe export parameters of the BAPI contain information about the status of an object instance.

To report messages from the method call back to the calling program, you should create theexport parameter RETURN. For more information about this parameter see Return Parameters(Error Handling) [Page 130].

Extension ParametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

SAP AG BAPI Programming

Example of a GetStatus() BAPI

December 1999 97

Example of a GetStatus() BAPIThe BAPI GetStatus() of the business object type DebtorCreditAccount (BUS1010) is used hereas an example.

The graphic below shows this BAPI in the BAPI Browser.

BAPI Programming SAP AG

Programming ExistenceCheck() BAPIs

98 December 1999

Programming ExistenceCheck() BAPIsUseThe BAPI ExistenceCheck() checks whether an entry exists in the database for an SAP businessobject type, for example, whether the customer master has been created.

The ExistenceCheck() BAPI is an instance method.

FeaturesYou can implement this method as a BAPI and/or as a method of SAP Business Workflow. If youimplement this method as a BAPI, it only has to be implemented once, because anExistenceCheck() BAPI can also be used by SAP Business Workflow.

To get the highest possible performance from the BAPI ExistenceCheck(), you should reduce thenumber of columns to as few as possible before selecting the table rows.

select single bukrs from bkpf into lv_bukrs

where bukrs = bkpf-bukrs

and belnr = bkpf-belnr

and gjahr = bkpf-gjahr.

instead ofselect single * from bkpf

where bukrs = bkpf-bukrs

and belnr = bkpf-belnr

and gjahr = bkpf-gjahr.

Import ParametersThe BAPI’s import parameters in the function module only contain the key fields of the businessobject type.

Export ParametersTo report messages from the method call back to the calling program, you should create only theexport parameter Return . For more information about this parameter see Return Parameters(Error Handling) [Page 130].

ActivitiesWhen a business object type is created, as the default, it inherits a definition of the methodExistenceCheck() through the interface IFSAP. For this reason, you can create anExistenceCheck() BAPI using the BOR/BAPI Wizard, as the method name ExistenceCheck()already exists for the business object type.

We recommend therefore, that you redefine the existing method ExistenceCheck() manually inthe BOR, via the menu path Edit → Redefine.

•••• Enter the function module that implements the ExistenceCheck() BAPI.

SAP AG BAPI Programming

Programming ExistenceCheck() BAPIs

December 1999 99

•••• Create the method parameter RETURN (the key fields of the business object type are notincluded in the method definition in the BOR).

BAPI Programming SAP AG

Example of an ExistenceCheck() BAPI

100 December 1999

Example of an ExistenceCheck() BAPIThe BAPI ExistenceCheck() of the business object type CompanyCode (BUS0002) is used hereas an example.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Example of an ExistenceCheck() BAPI

December 1999 101

BAPI Programming SAP AG

Programming Create() BAPIs

102 December 1999

Programming Create() BAPIsUseThe BAPI Create() creates one instance of an SAP business object type. Likewise, the BAPICreateMultiple() creates several instances of a business object type simultaneously.

If a workflow method called Create already exists for the business object type in question, youcan use the name CreateFromData() for your BAPI. Create() is the preferred name for this BAPI.

The BAPIs Create() and CreateMultiple() are class methods (instance-independent).

For each Create() BAPI a method must be provided with which the created business objectinstance can be deleted or cancelled. To do this, depending on the business application practice,you should implement one of the BAPIs below:

•••• Delete(), which deletes a business object instance from the database. For more informationsee Programming Delete() BAPIs [Page 110].

•••• Cancel() which cancels a business object instance. For more information see ProgrammingCancel() BAPIs [Page 113].

FeaturesImport ParametersThe BAPI’s import parameters in the function module contain the data required to uniquelyidentify an instance. For this you can either enter all object keys or else you must ensure thatthese can be derived.

If required, you can also use a test run parameter to check the entry for an object instance beforeactually creating the instance in the database. For further information see Test Run Parameters[Page 135].

You can create a change parameter to identify the values to create the instance with and to telldifferentiate these values from the initial values when the BAPI is called. We recommend that youidentify the change-relevant fields by flagging them. For more information see ChangeParameters [Page 125].

Export ParametersTo make the object key available to the calling program, the entire key fields must be returned inthe export parameters.

To report messages from the method call back to the calling program, you should create theexport parameter RETURN. For more information about this parameter see Return Parameters(Error Handling) [Page 130].

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

SAP AG BAPI Programming

Programming Create() BAPIs

December 1999 103

Avoiding Incompatibilities with Customizing SettingsIt could be possible that certain values set by Customizing appear differently in the BAPIinterface. These values cannot be overwritten by a Create() BAPI.

To avoid any incompatibility with Customizing settings, you should implement a Create() BAPI inthe following way:

• The BAPI should transfer all the fields and check them against the Customizing settings. Ifthe Customizing settings write-protect a field, the data in this field cannot be overwritten bydata in the BAPI interface.

• For every incidence of incompatibility an error message must be returned to the callingprogram. For example, “Customizing settings do not allow the field 'MyAsset-AssetName' tobe modified ”.

• All the fields that are assigned default values by Customizing and are therefore write-protected, must be documented.

External Key AssignmentFor Create() BAPIs with an external key assignment the caller transfers the key (ID) to the objectinstance to be created, for example, to a document number.

Keep in mind that you have to convert the specified keys explicitly in upper case letters in thesource code of this type of Create() BAPIs. Otherwise keys are created that cannot be used indialog applications. This is because with dialog applications external keys are always convertedimplicitly in upper case letters.

LockingWe recommend that you implement Create() BAPIs without the locking function and create yourown BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Example of a Create() BAPI

104 December 1999

Example of a Create() BAPI

The BAPI Create() of the business object type InternalOrder (BUS20745) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Example of a Create() BAPI

December 1999 105

BAPI Programming SAP AG

Programming Change() BAPIs

106 December 1999

Programming Change() BAPIsUseThe BAPI Change() changes an existing instance of an SAP business object type, for example, asales order.

The BAPI Change() is an instance method, whereas the BAPI ChangeMultiple() is a classmethod (instance-independent).

FeaturesImport ParametersThe import parameters of the Change() BAPI must contain the key fields of the business objecttype.

If required, you can create also create these parameters:

•••• A test run parameter for checking the entry for an object instance before actuallycreating/changing the instance in the database.

•••• A change parameter to identify parameter fields containing modified values and parameterfields that have not been modified.

For more information about these parameters see Standardized Parameters [Page 29].

Export ParametersTo make the object key available to the calling program, the entire key fields must be returned inthe export parameters.

To report messages from the method call back to the calling program, you should create theexport parameter RETURN. For more information about this parameter see Return Parameters(Error Handling) [Page 130].

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

Avoiding Incompatibilities with Customizing SettingsIt could be possible that certain values set by Customizing appear differently in the BAPIinterface. These values cannot be overwritten by a Change() BAPI.

To avoid incompatibility with Customizing settings, you should implement a Change() BAPI in thefollowing way:

•••• The BAPI should transfer all the fields and check them against the Customizing settings. Ifthe Customizing settings write-protect a field, the data in this field cannot be overwritten bydata in the BAPI interface.

•••• For every incidence of incompatibility an error message must be returned in the returnparameter to the calling program. For example, “Customizing settings do not allow the field'MyAsset-AssetName' to be modified ”.

SAP AG BAPI Programming

Programming Change() BAPIs

December 1999 107

•••• All the fields that are assigned default values by Customizing and are therefore write-protected, must be documented.

LockingWe recommend that you implement Change() BAPIs without the locking function and create yourown BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Example of a Change () BAPI

108 December 1999

Example of a Change () BAPIThe BAPI Change of the business object type PurchaseRequisition (BUS2105) is used here asan example.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Example of a Change () BAPI

December 1999 109

BAPI Programming SAP AG

Programming Delete() BAPIs

110 December 1999

Programming Delete() BAPIsUseThe BAPI Delete() deletes an instance of an SAP business object type from the database.Likewise, the BAPI DeleteMultiple() deletes several instances of a business object type. Delete()BAPIs must always delete entire instances, for example, a whole material master.

(Whereas the BAPI Cancel() cancels an instance of a business object, that is the instance to becancelled remains in the database and an additional instance is created that is canceled. Formore information see Programming Cancel() BAPIs [Page 113]).

A delete() BAPI can delete immediately or at a later time by setting the deletion flag. The type ofdeletion you use in your BAPI is irrelevant to the caller, so you do not have to include thesedetails in the BAPI interface.

The BAPI Undelete() is used to reset a deletion flag that has been set for a specific object.

The BAPIs Delete() and Undelete() are instance methods, whereas the BAPIs DeleteMutliple()and UndeleteMutliple() are class methods (instance-independent).

FeaturesThe interfaces of the Delete() and Undelete() BAPIs should be identical.

Import ParametersThe BAPI's import parameters have to identify the business object instances to be deleted.

•••• If an instance is to be deleted, you have to create a parameter for each key field in thebusiness object type.

•••• If several instances are to be deleted, you must create a table for the key fields of thebusiness object type. You can do this using a range table.

If required, you can create also create these parameters:

•••• A test run parameter for checking the entry for an object instance before actually deleting theinstance from the database.

•••• When the BAPI DeleteMultiple() is used, it must be possible to use the selection criteria toselect the object instances to be deleted. To do this you can create selection parameters.

For more information about these parameters see Standardized Parameters [Page 29].

Implement the interface of a Delete() BAPI so that it is not possible to delete all theinstances simply by parameterizing the interface, for example by specifying defaultsettings.

Export ParametersTo report messages from the method call back to the calling program, you should create only theexport parameter Return . For more information about this parameter see Return Parameters(Error Handling) [Page 130].

SAP AG BAPI Programming

Programming Delete() BAPIs

December 1999 111

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

LockingWe recommend that you implement Delete() BAPIs without the locking function and create yourown BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Example of a Delete() BAPI

112 December 1999

Example of a Delete() BAPIThe BAPI Delete() of the business object type EmployeeTrip (BUS2089) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Programming Cancel() BAPIs

December 1999 113

Programming Cancel() BAPIsUseThe Cancel() BAPI cancels one instance of a business object.

Unlike the BAPI Delete() [Page 110], which deletes an object instance from the database, withthe BAPI Cancel():

•••• The canceled instance of the business object is not deleted

•••• An additional instance is created with which the instance of the business object is deleted

The Cancel() BAPI is used to cancel business processes such as goods movements or invoicereceipts.

The Cancel() BAPI is an instance method.

FeaturesImport ParametersThe data of the instance to be created comes from the data of the business object instance to becancelled.

You can also create further parameters to specify information relevant for the actual cancellationprocess, for example, the name of the user performing the cancellation.

If required, you can also create a test run parameter, which can check the details of the objectinstance before it is actually canceled. For more information about this parameter see Test RunParameters [Page 135].

Export ParametersTo report messages from the method call back to the calling program, you should create theparameter Return. For more information about this parameter see Return Parameters (ErrorHandling) [Page 130].

You have to put the key of the created instance in another export parameter.

LockingWe recommend that you implement Cancel() BAPIs without the locking function and create yourown BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Example of a Cancel() BAPI

114 December 1999

Example of a Cancel() BAPIThe BAPI Cancel() of the business object type GoodsMovement (BUS2017) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Programming Replicate()/SaveReplica() BAPIs

December 1999 115

Programming Replicate()/SaveReplica() BAPIsUseTo replicate an instance of a business object, for example, if you want to exchange data betweentwo distributed systems in the context of Application Link Enabling (ALE), you have to implementcertain standardized BAPIs (see also Using BAPIs in Distributed Systems (ALE) [Page 164].

The objective of replicating business object types is to make specific instances of an object typeavailable on one or more additional systems. The replicated instances are usually created underthe same object key.

The interface of these BAPIs depends on the characteristics and contents of the business objectthat is to be replicated. For this reason replicate BAPIs must be implemented for each businessobject.

Business objects instances can be replicated in two ways:

•••• By request ("Pull")

System "A" requests replicates from system "B". Then system "B" replicates therequested business object instances on system "A".

•••• Using subscription lists ("Push")

In this approach system "B" maintains a list of systems requiring replicates. At regularintervals system "B" replicates the business object instances to all the systems in the list.

Both of the above replication methods can be implemented with the BAPIs Replicate(),SaveReplica() and SaveReplicaMultiple(). These BAPIs are both class methods (instance-independent).

FeaturesReplicate()The BAPI Replicate() is called in the system which contains the originals of the business objectinstances to be replicated. The BAPI Replicate() is used for:

•••• Identifying the business object instances to be replicated and to organize the required data

•••• Calling the SaveReplica() methods in the receiving system

The BAPI Replicate() can only request the replication of instances of a business object. Theactual replication is carried out when the server system calls one of the SaveReplica() BAPIsdescribed below on the client system.

You must follow the steps below:

1. Select the data to be replicated.

2. Determine the receiver.

This is done in the ALE distribution model using the function moduleALE_SYNC_BAPI_GET_RECEIVER. For information on this function module seeDistribution Using BAPIs [Ext.] in the ALE Programming Guide. You can also restrict thenumber of receivers in the parameter Recipients of the Replicate() BAPI.

3. Loop via the receiver and call the relevant SaveReplica() BAPI.

BAPI Programming SAP AG

Programming Replicate()/SaveReplica() BAPIs

116 December 1999

4. Enter a value in the return parameter and complete the Replicate() BAPI.

Import ParametersThe interface of the Replicate() BAPI must contain the following parameters:

•••• Parameters which identify the business object instances to be replicated.

You could implement these, for example, using a range table for the key fields of thebusiness object types or using selection parameters that enable you to select instancesto be replicated. (See also Selection Parameters [Page 134]).

•••• Parameter Recipients

This parameter identifies the logical systems in which the business object instances areto be replicated. This parameter is based on the data element BAPILOGSYS. If thisparameter is set to “initial”, the receiver is determined using the ALE distribution model.

The interface of the Replicate() BAPI may also contain the following import parameters:

•••• Parameter RequestChanges

This parameter enables modifications of object instances already replicated to be copieddirectly from engineering change management and forwarded to the receiving system.You should only use this parameter if the business object type in question providesengineering change management.

Structure this parameter on the data element . This can have the following values:

− ' ' (no value)

No value is the standard setting and means that engineering change managementwill not be accessed.

− 'X'

This value means that the modified data is replicated directly from engineeringchange management.

This parameter must not be used together with the Recipients parameter, because thechange pointers in change management are reset, if change management is accessedby the receiver. Other receivers may then not be allowed access. Documentation on thisparameter must refer explicitly to this connectivity.

•••• Other BAPI-specific import parameters, for example, to specify the data range of theinstances to be replicated (for example, material with or without plant data).

Export ParametersThe BAPI Replicate() should contain the following export parameters:

•••• The Return parameter in which messages from the method call are returned to the callingprogram. For more information about this parameter see Return Parameters (Error Handling)[Page 130].

•••• A table with information on the object instances to be replicated.

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

SAP AG BAPI Programming

Programming Replicate()/SaveReplica() BAPIs

December 1999 117

LockingWe recommend that you implement Replicate() BAPIs without the locking function and createyour own BAPIs instead that lock the relevant data.

SaveReplica() and SaveReplicaMultiple()The class method SaveReplica() and the method SaveReplicaMultiple() generate replicates ofbusiness object instances. They are used to replicate objects in different systems that aresemantically identical. For technical reasons these objects may be created with different objectskeys (object IDs).

The BAPI SaveReplica() is used by a system to replicate one business object instance on atarget system or to modify one business object that has already been replicated. Whilst theSaveReplicaMultiple() BAPI can replicate several business object instances on the target systemor modify several instances that have already been replicated.

For each business object type to be replicated you have to implement one or both of thesemethods, according to your requirements.

If instances that have already been replicated are to be changed when a SaveReplica() orSaveReplicaMultiple() BAPI is called, the fields that are to be changed (that is, receive newvalues) and the fields that are to remain the same must be identified. You can do this by flaggingthe fields, as described in Change Parameters [Page 125].

Import ParametersFor the BAPI, all the data required for replicating an individual business object instance must beprovided in the import parameters. For the SaveReplicaMultiple() BAPI, all the relevant data forreplicating several instances must be provided in the import parameters. All the object keys maybe provided, they must, however be able to be derived.

If only parts of objects are to be replicated rather than whole objects, you can use other optionalimport parameters.

Export ParametersTo return messages from the method call to the calling program, you should only create theparameter Return for these BAPIs. For more information about this parameter see ReturnParameters (Error Handling) [Page 130].

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

LockingWe recommend that you implement SaveReplica() BAPIs without the locking function and createyour own BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Example of a SaveReplica() BAPI

118 December 1999

Example of a SaveReplica() BAPIThe BAPI SaveReplica() of the business object type InternalOrder (BUS2075) is used here as anexample.

The graphic below shows this BAPI in the BAPI Browser.

SAP AG BAPI Programming

Example of a SaveReplica() BAPI

December 1999 119

BAPI Programming SAP AG

Programming Methods for Sub-Objects

120 December 1999

Programming Methods for Sub-ObjectsUseIf a business object type consists of sub-objects, you can implement the following standardizedBAPIs to add or remove sub-objects:

•••• Add<name of sub-object>

This method adds a sub-object to an object type.

•••• Remove<name of sub-object>

This method removes a sub-object from an object.

For example, to add or remove the sub-object purchase order item to the businessobject type purchase order, the BAPIs AddItem() and RemoveItem() could beimplemented for the object type, purchase order.

The BAPIs Add<Name of sub-object> and Remove<Name of sib-objects> are instance methods.

FeaturesImport ParametersBoth BAPIs’ import parameters must contain in the function module the data that uniquelyidentifies the sub-object as well as the key fields of the business object.

If required, you can create also create these parameters:

•••• A test run parameter for checking the entry for an object instance before actually creating theinstance in the database.

•••• A change parameter to identify parameter fields containing modified values and parameterfields that have not been modified.

For more information about these parameters see Standardized Parameters [Page 29].

Export ParametersYou should only create the export parameter RETURN in the BAPI Remove<Name of sub-object> to return messages from the method call to the calling program. For more informationabout this parameter see Return Parameters (Error Handling) [Page 130].

To make the object key available to the calling program, the key fields of the object type mustalso be returned in the export parameters of the BAPI Add<Name of sub-object> as well as in theexport parameter Return.

Extension parametersYou can create extension parameters to enable customers to enhance the functionality of BAPIswithout making modifications. For information about extension parameters see CustomerEnhancement Concept for BAPIs [Page 65].

SAP AG BAPI Programming

Programming Methods for Sub-Objects

December 1999 121

LockingWe recommend that you implement methods of sub-objects without the locking function andcreate your own BAPIs instead that lock the relevant data.

BAPI Programming SAP AG

Programming Standardized Parameters

122 December 1999

Programming Standardized ParametersPurposeThere are some parameters that can be created for various BAPIs because they contain thesame or equivalent data in all BAPIs. Such parameters are known as “standardized” parameters.They should be implemented the same in all BAPIs.

Process FlowIf your BAPI is a standardized BAPI, you should implement it following the programmingguidelines described in the following sections.

SAP AG BAPI Programming

Address Parameters

December 1999 123

Address ParametersUseSpecific reference structures are defined for address parameters in BAPIs. You should copythese structures to use in your BAPI, especially if the underlying object type uses the centraladdress management (CAM).

Use one of the following structures as a copy reference for addresses in BAPIs:

Reference Structure UseBAPIADDR1 Addresses of companies and organizationsBAPIADDR2 Addresses of individualsBAPIADDR3 Addresses of contact persons within an organizationBAPIADDR1X Change reference structures for addresses of companies and

organizationsBAPIADDR2X Change reference structures for addresses of individualsBAPIADDR1X Change reference structures for contact persons within an

organization

Keep in mind the following points when you use these reference structures:

•••• All the fields of the reference structures refer to the central address management (CAM).Only use fields that can also be processed in your application context. If the CAM isalready included, then all the fields are relevant.

•••• Contrary to the standard guidelines (compare with Internal and External Data Formats[Page 69]), for some coded name parts the text formats (for example, CHAR 20 or CHAR39) are included as fields in these structures, rather than the internal database keys.

These fields are:

− Address text (fields TITLE_P, TITLE and FORMOFADDRESS)

− Academic title (fields TITLE_ACA1 and TITLE_ACA2)

− Name prefixes, for example "von", "van der" (fields PREFIX1 and PREFIX2)

− Names affixes, for example, titles (field TITLE_SPPL)

You cannot expect in these cases that a calling program converts the internal databasekeys into the external readable form and vice versa. In these cases you can use thefunction modules below which enter values in these structures or accept changes madeto the structures and then assign the correct keys internally.

Function Module DescriptionADDR_CONVERT_FROM_BAPIADDR1 Converts the fields in the structure from the

external format into the internal format.ADDR_CONVERT_TO_BAPIADDR1 Converts the fields in the structure from the

internal format into the external format.ADDR_CONVERT_FROM_BAPIADDR2 Converts the fields in the structure from the

external format into the internal format.

BAPI Programming SAP AG

Address Parameters

124 December 1999

ADDR_CONVERT_TO_BAPIADDR2 Converts the fields in the structure from theinternal format into the external format.

ADDR_CONVERT_FROM_BAPIADDR3 Converts the fields in the structure from theexternal format into the internal format.

ADDR_CONVERT_TO_BAPIADDR3 Converts the fields in the structure from theinternal format into the external format.

•••• If fields are lengthened in the CAM, the associated field in the BAPI reference structureremains the same type and length. A new data element is assigned to this field that canbe identified as obsolete in the description and/or short text. The obsolete field is stilltaken into account in the conversion modules described above.

For the new field length a new field with a new name is added to the end of the structure.Currently this affects the following fields:

Existing Field Length New Field Length In StructureFORMOFADDR Char 20 TITLE Char 30 BAPIADDR1BUILDING Char 10 BUILD_LONG Char 20 BAPIADDR1, BAPIADDR2,

BAPIADDR3STREET Char 40 STREET_LNG Char 60 BAPIADDR1

Preferably, you should use the new, longer fields.

•••• When using the reference structure BAPIADDR3, remember that read-only access ispossible to all the fields in the company’s address (check table ADRC). If you want tomake changes to these fields you have to access the reference structure BAPIADDR1.

SAP AG BAPI Programming

Change Parameters

December 1999 125

Change ParametersUseIn BAPIs that cause database changes (for example, Change() and Create() BAPIs), you mustbe able to distinguish between parameter fields that are to be modified (change-relevant fields)and parameter fields that are to remain unmodified.

Using an initial value is no solution because an initial value could also represent a valid newvalue. Also, in the ABAP programming language as well as on other development platforms, thevalue “NULL” should not be assigned to a data type to indicate an empty field.

Standardized change parameters are used to identify fields with modified values in Change() andCreate() BAPIs. You can do this in two ways:

•••• Flagging Fields to Identify Fields Containing Modified Values

•••• Comparing Fields to Identify Fields Containing Modified Values

Flagging Fields to Identify Fields Containing Modified ValuesIn this approach parameter fields containing modified values are identified by including a flag inan additional "change parameter".

•••• An additional change parameter must be created with the same number of fields and thesame field names for every parameter in the BAPI containing modified field values.

•••• When the BAPI is called, the fields in the additional change parameter whose counterparts inthe corresponding parameter contain modifications, must be marked with an update flag.

This way the BAPI can identify both modified and unmodified fields in the parameter.

Follow the conventions below when you create change parameters to identify modified fields:

•••• The name of the additional change parameter consists of the parameter name with the suffix"X". For instance, if the parameter is called EquiSales, the name of the additional changeparameter is EquiSalesX.

•••• The additional change parameter must contain exactly the same number of fields and thesame field names as the parameter. You must use the data element BAPIUPDATE (CHAR1) as the data element for the update fields. This can have the following values:

•••• 'X'

This value means that the corresponding parameter field contains a modified value.

•••• ' ' (no value)

This means that the corresponding parameter field does not have to be updated.

•••• If the parameter is a table, the additional change parameter must also be a table.

A Change() BAPI is used to change the value of the existing distribution channel(Distr_Chan) to Distr_Chan="US". The fields that have been changed should beidentified by flagging them.

The program objects in the R/3 System affected by this change are:

BAPI Programming SAP AG

Change Parameters

126 December 1999

Program Object Name

SAP business object type PieceOfEquipment

BAPI Change

Parameter EquiSales

Fields in parameterEquiSales

SalesOrg=0001'

Distr_Chan='US'

Division=' Marketing'

Change parameter that identifies modified fields EquiSalesX

Fields in parameterEquiSalesX

SalesOrg=' '

Distr_Chan='X'

Division=' '

In the parameter EquiSalesX the value in the field Distr_Chan is 'X'. This indicatesthat the field Distr_Chan of the parameter EquiSales contains a modified value (US).

The Change() BAPI then overwrites the existing value in the field Distr_Chan with thecurrent value in the field Distr_Chan in the parameter EquiSales.

Comparing Fields to Identify Fields Containing Modified ValuesIn this approach fields containing modified values are identified by comparing two parameters,one containing the current valid data and the other the new, modified data.

When the Change() BAPI is called, the current data in the database and the new, modified datamust be entered in the corresponding parameters. The current data set can be transferred, forinstance, from a GetDetail() BAPI that has been called.

The following comparisons can be made:

•••• The current data can first be checked against the database contents to ascertain whether ithas changed in the meantime. This way any database changes made between the time thedata was read by the GetDetail() BAPI and the time the database is updated can beidentified.

•••• The data in both the parameters can be compared field by field. If the data in twocorresponding fields is different, the relevant values must be transferred from the parameterwith the new data.

Note the following when you are comparing fields containing modified data.

•••• A calling program must be able to provide data in all the parameter fields of the Change()BAPI. For this reason, the parameter fields of the Change() BAPI must be exactly the sameas the fields in the GetDetail() BAPI of the same business object type.

•••• The names of the parameters to be compared must be the same, but the parametercontaining the modified data must also have the suffix ‘New’.

SAP AG BAPI Programming

Change Parameters

December 1999 127

For example, if the parameter with the current valid data is called EquiSales, theparameter with the modified data is called EquiSalesNew.

•••• Both parameters must have exactly the same fields and the same structure.

A Change() BAPI is used to change the value of the existing distribution channelDistr_Chan="US" to Distr_Chan=“EN”. The fields containing modified should beidentified by comparing them.

The program objects in the R/3 System affected by this change are:

Program Object Name

SAP business object type PieceOfEquipment

BAPI Change

Parameter EquiSales

Fields in parameterEquiSales

SalesOrg=' 0001'

Distr_Chan='US'

Division=' Marketing'

Parameter for the new data EquiSalesNew

Fields in parameterEquiSalesNew

SalesOrg=' 0001'

Distr_Chan='EN'

Division=' Marketing'

The fields are compared by:

1. Entering data from the relevant GetDetail() BAPI in the parameter EquiSales.

2. Initializing the parameter EquiSalesNew with the values from the parameterEquiSales.

3. Modifying the required parameter values in the parameter EquiSalesNew, forexample: EquiSalesNew-Distr_Chan='EN'.

Which is the Best Way?The table below compares the two ways of identifying fields containing modified values in BAPIs,as described above, and should help you decide which way suits your requirements best.

Area Comments

Performance Flagging fields: The flag table can be compressed. Datadoes not have to be compared.

If using in a distributed environment (ALE) the amount ofdata to be transported by flagging fields is notsignificantly greater.

BAPI Programming SAP AG

Change Parameters

128 December 1999

Programming Flagging fields: BAPI programming is simpler.

Check facilities Comparing fields: Can check against current databaseto identify and prevent inconsistencies.

Comprehension Flagging fields: Fields containing modifications can beflagged, meaning less demands are placed on the caller.

Comparison with related data Comparing fields: Need to compare with the associatedGetDetail() method of the business object type, becauseall the fields in the Change BAPI() must filled by thecalling program.

Application Flagging fields: Better for performance criticalapplications.

Comparing fields: Better for dialog-orientatedapplications with critical data.

SAP AG BAPI Programming

Extension Parameters

December 1999 129

Extension ParametersUseThe parameters ExtensionIn and ExtensionOut enable customers to enhance BAPI interfaceswithout modifications and to process customer-specific data automatically.

For details see Customer Enhancement Concept for BAPIs [Page 65].

BAPI Programming SAP AG

Return Parameters (Error Handling)

130 December 1999

Return Parameters (Error Handling)UseA BAPI should be able to record and classify all possible errors that may occur.

You have to create a parameter named Return for every BAPI. This parameter returns exceptionmessages or success messages to the calling program.

BAPIs themselves must not trigger any messages (such as MESSAGE xnnn) in the coding. Inparticular they must not generate terminations or display dialog boxes. Instead, all messagesmust be intercepted internally and reported back to the calling program in the Return parameter.Otherwise the BAPI will not be processed correctly and control may not be given back to thecalling program.

All error messages or indeed any message that may be returned by the BAPI, must be defined inmessage table (Tools → ABAP Workbench →=Development →=Programming environment→=Messages) and described in the documentation for the return parameter. This also applies tothe most important or most likely error messages generated by other programs that can beindirectly passed via the BAPI to the application program.

As of Release 4.0 you must not use exceptions in BAPI interfaces.

When a termination message (message type A) is triggered, a database rollback isexecuted in the standard programming model, that is, all tasks performed since thelast COMMIT WORK are canceled. When you program BAPIs, we recommend thatyou also execute a database rollback in the return parameter for terminationmessages. You must describe this process in the documentation for the Returnparameter. For messages of type E (error), the calling program performs the errorhandling.

Application developers are provided with two service BAPIs to diagnose and process errormessages from BAPI calls:

•••• BapiService.MessageGetDetail() which displays the short and long texts of BAPI errormessages.

•••• BapiService.ApplicationLogGetDetail(), with which information in application logs can bedisplayed.

FeaturesThe export parameter Return can be implemented as follows:

•••• As a structure, whereby it must be defined in the function module as an export parameter, aswell as in the method in the BOR.

•••• As a table, whereby it must be defined in the function module as a table parameter, as wellas in the method in the BOR as an export parameter.

Before filling the Return parameter you should either initialize the structure with CLEAR or thetable with REFRESH and CLEAR.

SAP AG BAPI Programming

Return Parameters (Error Handling)

December 1999 131

If the return parameter is not set or is set to an initial value this means that no error has occurred.

The Return parameter may be based on the following reference structures:

•••• BAPIRET2

We recommend that you use this reference structure as of Release 4.5A.

•••• BAPIRET1

Both structures must be filled in the logon language.

Reference Structure BAPIRET2The structure BAPIRET2 is filled via the function module BALW_BAPIRETURN_GET2. Itcontains the following fields:

Field Type Description

TYPE CHAR 1 S = success messageE = error messageW = warning messageI = information messageA = termination message (abort)

ID CHAR 20 Message ID The structure BAPIRET2 takes into accountthe name space extension for the message class as ofRelease 4.0. If you want messages to be compatible withearlier R/3 Releases, use the message classes beforeRelease 4.0.

NUMBER NUMC 3 Message number

MESSAGE CHAR 220 Full message text from the message table. All variables(in fields Message_V1 to Message_V4) have beenreplaced with text.

LOG_NO CHAR 20 Application log number This is empty if no log used.

Note that for type A error messages (abort), anapplication log is not created, as in this case there is noCOMMIT WORK.

LOG_MSG_NO NUMC 6 Current message number in application log

MESSAGE_V1MESSAGE_V2MESSAGE_V3MESSAGE_V4

CHAR 50 Fields for the variable texts of the message specified infields ID and NUMBER.

PARAMETER CHAR 32 Parameter containing the invalid value.

ROW INT 4 Line number of the data record containing the invalidvalue

FIELD CHAR 30 Field containing the invalid value.

BAPI Programming SAP AG

Return Parameters (Error Handling)

132 December 1999

SYSTEM CHAR 10 System (logical system) in which the message wasgenerated.

Reference Structure BAPIRET1This structure is filled via the function module BALW_BAPIRETURN_GET1. It consists of thefields in the BAPIRET2 structure excluding the fields PARAMETER, ROW and FIELD.

Return Parameters in the ALE Distributed EnvironmentAfter the function module which converts the IDoc into the corresponding BAPI in the receivingsystem has been called, status records are written for the IDoc in which messages sent in thereturn parameter are logged (see also Using BAPIs in Distributed Systems (ALE) [Page 164].

If the field type is filled with E (error) or A (abort) in at least one of the transferred returnparameter entries, the status 51 (application document has not been posted) is assigned to allthe status records of the IDoc and a ROLLBACK WORK is executed. If the field type is filled withE (error) in at least one of the transferred return parameter entries, the status 51 (error,application document has not been posted) is assigned to all the status records of the IDoc and aCOMMIT WORK is executed anyway. Otherwise status 53 (application document posted) iswritten and a COMMIT WORK executed.

Application Log and Application-Specific Error TablesIf the information provided in the Return parameter is not sufficient, you can log errors with theapplication log. The logging should be done by the BAPI itself so that function modules calleddirectly by this BAPI do not have to be modified. The fields LOG_NO and LOG_MSG_NO of theReturn parameter return the application log numbers and their messages.

As of Release 4.6A you can already maintain the log number when you create theapplication log. Several instances of an application object can be maintained at thesame time and can be updated together. The update task can be also used forapplication logs, that is, log entries are and no longer directly written to the database,they are written via the update task. If you plan to use application logs in your BAPI,you must write these using the update task.

For further information on application logs see Creating Applications Logs [Ext.] in the documentBC - Extended Function Library Applications [Ext.].

If this still does not provide enough information, the calling application can define its ownadditional error tables. There are no set guidelines for these additional tables. The Returnparameter in your BAPI could give details of the messages in the error tables, for example, ifthere are error messages (type E) in the table. The calling program then has immediate controlover the contents of the error table and does not have to first search for error messages.

The use of the application log and error tables enable error messages to be returned if theycannot be adequately returned in the return parameter.

SAP AG BAPI Programming

Return Parameters (Error Handling)

December 1999 133

Note that for type A error messages (abort), an application log is not created, as inthis case there is no COMMIT WORK.

BAPI Programming SAP AG

Selection Parameters

134 December 1999

Selection ParametersUseThe parameters in BAPIs used to search for specific instances of a business object type, forexample, BAPI GetList(), have to enable the caller of the BAPIs to specify appropriate selectioncriteria.

In your BAPI create the required selection parameters as structures or tables with the followingparameters:

Fields for Value RangesField Name Description Data Element

SIGN Selection operator that determineswhether the range specified is to beincluded or excluded.

BAPISIGN

OPTION Relational operator, for example.Relational operator, e.g. CP (containspattern) or NP (no pattern)

BAPIOPTION

HIGH Upper limit of value range application-specific, forexample, MATNR.

LOW Lower limit of value range application-specific, forexample, MATNR.

You can use the function module BALW_RANGES_CHECK to check the values entered in SIGNand OPTION.

Note that when you select a list of objects you have to limit the number of objects selected. Youcan use the parameter MaxRows to do this. For more information see Programming GetList()BAPIs [Page 91].

Application servers might not support ASCII, but use a different character set instead.If this is the case a problem may arise when you select quantities or ranges or whenthese are sorted. Because of this a BAPI should always select a range between A-Z,a-z and 0-9.

SAP AG BAPI Programming

TestRun Parameters

December 1999 135

TestRun ParametersUseThe parameter TestRun is used in write BAPIs, for example, Create() or CreateFromData(), tocheck the entries for the object instance in the database before actually creating the objectinstance. The generation of the instance, for example, creating master data, is only simulatedand the data is not written to the database.

To simulate the creation of the object instance and to supply the relevant return messages, theBAPI should carry out all the necessary checks (excluding technical checks, such as,establishing the connection to the R/3 System), without actually updating the database.

For BAPIs used in an ALE distributed environment, this parameter must be availablein the interface.

Updating can be switched on or off using the TestRun parameter. The parameter is based on thedata element TESTRUN. This can have the following values:

•••• ' ' (no value)

No value means that the data will be posted. This is the default setting.

•••• 'X'

This value means that the BAPI is being called only in simulation mode and updating willnot take place.

Keep in mind the following as you are programming:

• Do not assign any internal numbers either for the object itself, or for any dependentobjects (for example, EAN numbers or Mat.Ledger No. in the material master).

• Be careful when calling function modules in other applications as these could assignnumbers or update the database.

• Do not inadvertently write change documents.

• Create a message in the return parameter of the BAPI that informs users whether theBAPI has been implemented in simulation mode.

BAPI Programming SAP AG

Text Transfer Parameters

136 December 1999

Text Transfer ParametersUseText transfer parameters are used to pass information in a BAPI (e.g. documentation on abusiness object type) from the R/3 System to a calling program.

FeaturesTo transfer documentation texts you have to create the standardized parameters below:

•••• The import parameter TextFormat that identifies the data format of the text to be transferred.

Use the type BAPI_TFRMT for this parameter. This requires the following fixed valuesthat must all be provided by the BAPI:

•••• SCR for SAPscript

•••• ASC for ASCII

•••• RTF for rich text format

•••• HTM for hypertext markup language (HTML)

•••• The table parameter Text that carries the text to be transferred.

Use the reference structure BAPITGB for this parameter.

You can see an example of using text transfer parameters in the BAPIBapiService.FieldhelpGetDocu().

SAP AG BAPI Programming

Tools for Developing BAPIs

December 1999 137

Tools for Developing BAPIsUseYou can use the following development tools to develop BAPIs in addition to the standarddevelopment tools in the ABAP Workbench:

•••• The BOR/BAPI Wizard to define BAPIs in the Business Object Repository.

This program is described in Defining Methods in the BOR Using the BOR/BAPI Wizard[Page 138].

•••• A transaction to automatically generate function modules to convert between internal andexternal data formats.

This transaction is described in Converting Between Internal and External Data Formats[Page 140].

•••• The report BBAPIFLD used to generate default values for English field names and parameternames.

For further information see the section Specifying Development Objects in the ABAPDictionary [Page 37] in the report documentation.

BAPI Programming SAP AG

Defining Methods in the BOR Using BOR/BAPI Wizard

138 December 1999

Defining Methods in the BOR Using BOR/BAPI WizardPrerequisitesIf the function module which your BAPI is based on has been fully implemented or modified youcan define it as a method of an SAP business object type or SAP interface type in the BusinessObject Repository (BOR). You use the BOR/BAPI-Wizard to do this.

ProcedureFirst find the relevant SAP business object type in the BOR:

1. Select Tools → Business Framework → BAPI Development →==Business Object Builder.

On the initial Business Object Builder screen you can directly access the SAP businessobject type or interface type if you know the technical name of the object (object type).You have already identified the technical name in Defining a BAPI and Its Interface[Page 24]

Otherwise select Business Object Repository.

•••• To display object types, in the next dialog box indicate whether you want to display all objecttypes or only business object types. Then select Continue.

•••• To display SAP interface types, in the next dialog box select Other settings and thenInterface.

The application hierarchy is displayed. Search for the required business object type orinterface type in the application hierarchy and double click it to open it.

2. When the business object type or interface type is displayed, select Change.

Creating BAPIs as Methods of Business Object Types or Interface TypesTo define your BAPI as a method of a business object type or interface type:

1. Select Utilities → API Methods → Add method.

2. In the next dialog box enter the name of the function module, for example,BAPI_COMPANYCODE_GETDETAIL and select Continue.

3. In the next dialog box specify the following information for the method to be defined:

•••• Method

A default name for the method is provided, based on the name of the functionmodule. You will have to modify the suggested name.

•••• Delete the prefix “BAPI” and the business object name, so that only the method name isleft. Begin every new word of the method name with a capital letter and do not useunderscores.

Example: If the name of the function module is BAPI_SALESORDER_GETSTATUS,the suggested method name might be BapiSalesorderGetstatus. You should edit thisso that the resulting name is GetStatus.

•••• Texts

Enter meaningful descriptions for your BAPI.

SAP AG BAPI Programming

Defining Methods in the BOR Using BOR/BAPI Wizard

December 1999 139

•••• Radio buttons Dialog, Synchronous, Instance-independent

Enter relevant details for your BAPI. Make sure that a BAPI is not dialog orientated.BAPIs are usually implemented synchronously.

4. Select Next Step.

A list of parameters and default names is displayed which you need to edit as required.Modify the parameter names as follows:

•••• Each new word in the parameter name must start with a capital letter, for example,CompanyCodeDetail.

•••• Make sure that the parameter names of the method in the BOR are identical to theparameter names in the function module except for the upper/lower case letters.

•••• Also specify whether the individual table parameters are used for data import or dataexport. Table parameters are marked with a tick in the column 'MLine' (multiple lines).

5. Select Next Step.

To create the method select Yes in the next dialog box.

ResultAfter the program has been generated and executed, check that all the definitions have beenmade correctly by the BOR/BAPI Wizard. To do this look at the newly created method of thebusiness object type or interface type.

The BOR/BAPI Wizard is used only to create new BAPIs for the first time. It is notused to make changes to existing BAPIs.

If you make changes to the underlying function module after you have created theBAPI in the BOR, for example, if you make compatible interface enhancements ormodify short texts, such changes do not automatically take effect in the BOR. Youhave to make these changes manually in the BOR. For information about creatingand modifying business object types refer to the documentation on SAP BusinessWorkflow [Ext.].

BAPI Programming SAP AG

Converting Internal and External Data Formats

140 December 1999

Converting Internal and External Data FormatsPrerequisitesThis section describes how you can generate function modules to convert between internal andexternal data formats. These function modules are used to:

• Map English and German field names onto each other

• Carry out ISO code conversions

• Convert currency amounts into the required external or internal format

• Convert internal and external keys, for use for example by WBS elements (workbreakdown structure)

Note that conversions between internal and external data formats should only be carried out inexceptional circumstances. These exceptions are described in Internal and External DataFormats [Page 69].

To generate the function modules, the relevant internal and external data formats must havebeen created in the ABAP Dictionary.

ProcedureTo generate the function module follow the steps below:

1. Select Tools → Business Framework → BAPI Development →==Generate module to mapfields.

2. In the appropriate input fields enter the names of the external BAPI structure and the internalworking structure you are making the conversion between. Specify the required direction formapping, i.e. is the internal structure to be mapped onto the external structure or vice versa.

3. Select Function module →=Generate.

A dialog box is displayed in which you can enter details of the function module to begenerated. The input fields for the name of the function module and the short text containsuggested values which you can accept or change.

In the field Function group enter the name of the function group to which the generatedfunction module is to be added. If the function module is being used to convert currencyamounts, the fixed point arithmetic for the selected function group must be switched on.

In addition to the source text for the function module you can have a blank FORM routineadded for your own program code if you have to make manual modifications. To do this,select Form to edit. The FORM routine contains the same parameters as the generatedfunction module.

4. Select Continue.

A table is displayed containing suggestions for the conversion of each field of theexternal BAPI structure. The table contains the following columns:

• Status

Indicates if the conversion is possible or if data is missing.

• Field in external structure

SAP AG BAPI Programming

Converting Internal and External Data Formats

December 1999 141

Contains the field names of the external BAPI structure.

• Conv. type

Displays the conversion type.

• Field in internal structure

Displays the fields of the internal structure to which/from which mapping is to becarried out.

For further information select F1 help for columns Status and Conv. type.

5. To generate the function module, select Save.

The function module is stored in the Function Builder in the function group you specified.

ResultIn a few cases it may be necessary to manually edit the source code of a function module thathas been automatically generated.

It is not yet possible to use this transaction to regenerate an existing function module. Toregenerate an existing function module you must first manually delete the function module andthen generate it afresh.

You can incorporate the generated function modules into the source code of your BAPI asrequired.

• To map the internal work structures to the external BAPI structures before calling theBAPI

• To map the result to the internal work structure after the BAPI has been called

• To map the inbound parameters to the internal structures (import parameter structures)when you are implementing the BAPI

• To map the result from the internal structure to the BAPI (export parameter structures)when you are implementing the BAPI

The section Application Example [Page 142] illustrates how function modules are used.

BAPI Programming SAP AG

Application Example

142 December 1999

Application ExampleThe BAPI used in this fictitious example can read the standard price of a material:

bapi_material_getprice

importing

material like mara-matnr

exporting

material_price like bapi_material_price.

The external structure bapi_material_price contains the following fields:

Fields in External BAPI StructureField Description Data Element Domaincurrency_iso ISO currency code isocd isocdcurrency Currency code waers waersamount Amount bapimatprice bapicurr

The application programmer in the R/3 System who intends to use this BAPI uses the internalstructure mat_preis in his or her own program. This structure consists of the following fields:

Fields in Internal Working StructureField Description Data Element Domainmatnr Material number matnr matnrwaers Currency code waers waersstprs Unit price stprs strps

The BAPI structure bapi_material_price contains an ISO currency code and a currencyamount. After calling the BAPI, the application programmer must convert these fields into theinternal format used in R/3 so that the fields can be processed.

Using the function, Generate module to map fields, (see section Converting Between Internal andExternal Data Formats [Page 140]), the application developer can generate the function module,map2i_bapi_material_price_to_mat_preis, which converts the currency and amount fields. Thisfunction module has the following interface:

function map2i_bapi_material_price_to_mat_preis

importing

external structure bapi_material_price

changing

internal structure mat_preis

exceptions

error_during_iso_convertion

error_converting_currency_amount.

The application code could be as follows:

SAP AG BAPI Programming

Application Example

December 1999 143

...

data: matnr like mara-matnr,

price like mat_preis,

bapi_price like bapi_material_preis....

* Call BAPICall function bapi_material_getprice

exporting

material = matnr

changing

material_price = bapi_preis.

* Map and convert the result to internal formatcall function map2i_bapi_material_price_to_mat_preis

exporting

external = bapi_preis

changing

internal = preis.

* exceptions

* error_during_iso_convertion

* error_during_currency_amount_conversion

preis-matnr = matnr....

BAPI Programming SAP AG

SAP Enhancements to Released BAPIs

144 December 1999

SAP Enhancements to Released BAPIsPurposeApplication developers who are using BAPIs in their application programs must be able to rely onthe fact that the BAPI's interface is not going to change. As a result of this, once a BAPI isreleased, it must fulfill certain requirements regarding the stability of its interface.

If you continue developing your BAPI after you have released it, you need to ensure that anysyntax changes or changes to the contents or functionality of the BAPI are downward compatible.Downward compatibility means that applications that were programmed with BAPIs from aspecific R/3 Release will not be effected in later R/3 Releases if the syntax or the content of thisBAPI changes.

Examples of syntax changes are changes to parameter names, or changes to the type or lengthof a domain. The ABAP Dictionary can automatically test whether syntax changes arecompatible.

However, only the developer can ensure that content changes are downward compatible.

Accordingly, when you enhance a BAPI, you can only differentiate between a compatible and anincompatible enhancement, if the downward compatibility of the BAPI can be verified.

Process FlowWhen you are enhancing a BAPI, you should attempt to make compatible changes in order tolimit the impact of your modifications on existing programs which use the BAPI.

For example, when adding a new import parameter, consider whether the interface wouldfunction without the parameter. If this is the case, you can make the enhancement to theinterface compatible by adding an optional parameter.

For further details see Compatible Enhancements [Page 146] and Incompatible Enhancements[Page 148].

For SAP internal development, each enhancement to a BAPI must be created in aproject in the BAPI Explorer.

Modifications and Version Management in the BORChanges made to a BAPI only take effect when the changes are defined in the Business ObjectRepository (BOR), that is, they are saved and generated.

Version management of BAPIs is also carried out in the BOR.

Checks in the ABAP DictionaryChanges to the syntax of BAPIs are automatically checked by the ABAP Dictionary, therebypreventing the BAPI data structure being changed by mistake.

•••• Incompatible changes to data elements, domains or structures that are being used by a BAPIthat has been released, are rejected by the ABAP Dictionary.

SAP AG BAPI Programming

SAP Enhancements to Released BAPIs

December 1999 145

•••• Compatible changes or changes to data elements, domains or structures of a BAPI that hasnot been released are accepted by the ABAP Dictionary.

BAPI Programming SAP AG

Compatible Enhancements

146 December 1999

Compatible EnhancementsUseCompatible enhancements are interface enhancements that change the BAPI without effectingthe downward compatibility of the BAPI. Applications which access the BAPI are not affected bycompatible enhancements.

FeaturesCompatible enhancements are:

•••• New optional parameters

A parameter is considered to be optional if it does not have to be included in a BAPI call.

A new optional parameter can be added in any place in the interface.

A new parameter is added to the BAPI SalesOrder.GetList() which can be used asan additional selection criteria for selecting sales orders in the R/3 System.

•••• New optional fields in structures

A field is considered to be optional if it can be left out completely in a BAPI call.

The fields must be added to the end of a structure because the function moduleunderlying the BAPI is called via RFC.. It does not matter how the fields are arranged ina structure or table because the whole structure is always forwarded. It is not first brokenup into fields.

An additional input field for the applicant's educational background is added to theBAPI Applicant.CreateFromData().

The table below lists the compatible changes that can be made to function modules. We cannotguarantee that this list is complete.

Compatible Changes to FunctionModules

In interface New optional parameter as a field

New optional parameter as a structure

New optional parameter as a table

Adding new optional field to the structure.

Adding new optional field to the table.

Compatible changes to field types (in ABAP Dictionary).

Converting mandatory fields to optional fields

In program code New additional coding, that does not involve changes tothe interpretation/processing logic.

SAP AG BAPI Programming

Compatible Enhancements

December 1999 147

Changes to the existing code, which do not involvechanging the interpretation or processing logic.

Using customer exits.

BAPI Programming SAP AG

Incompatible Enhancements

148 December 1999

Incompatible EnhancementsPurposeChanges to the contents or functionality of a BAPI often result in the introduction of newparameters without which the interface can no longer function. Often, these changes also causeexisting parameters to lose their original meaning. Such modifications are considered to beincompatible enhancements, because they no longer enable the BAPI to be downwardcompatible.

Incompatible enhancements are:

•••• Changes to the field length

•••• Changes to the field type

•••• Renaming parameters in the function module or in the method

•••• Inserting a field within a structure

•••• Deleting parameters and fields

•••• Adding new mandatory parameters or fields

Parameters can be flagged as mandatory parameters in the BOR However, this is notthe case with fields. Fields can only be categorized as mandatory at a semantic level andnot at a technical level. This is why the documentation for each parameter must specifywhich fields can be filled.

The table below lists the incompatible changes to function modules. We cannot guarantee thatthis list is complete.

Incompatible Changes toFunction Modules

In interface New mandatory parameter

Adding new fields between existing fields in structure.

Adding new fields between existing fields in the table.

Adding new mandatory field to the structure.

Adding new mandatory field to the table.

Incompatible changes to field types (in ABAP Dictionary).

Converting mandatory fields to optional fields

Renaming a parameter

In program code New additional coding, involving changes to theinterpretation/processing logic.

Changes to the existing code that involve changing to theinterpretation/processing logic.

Adding or removing COMMIT WORK commands in theprogram.

SAP AG BAPI Programming

Incompatible Enhancements

December 1999 149

Process FlowIf changes to BAPIs are incompatible, proceed as follows:

Creating an Additional BAPITo ensure that the interface stability of an existing BAPI is not effected, you must not make anyincompatible changes to the existing BAPI. Instead, create one or several, if required, additionalBAPIs to replace the existing one.

The new BAPI must retain the same name as the existing BAPI. A numeric suffix is simply addedto it. This suffix changes if further incompatible changes are made.

A number of incompatible changes must be made to the BAPI FixedAsset.Create().To implement these changes, a new BAPI, FixedAsset.Create1(), is created, in orderto maintain the interface integrity of the BAPI FixedAsset.Create().

If further incompatible modifications must be made to the BAPI at a later date, yetanother BAPI, FixedAsset.Create2(), must be created.

Supporting and Labeling the Expiring BAPIAfter the BAPI has been superseded by a new BAPI, you should not remove the replaced BAPIfrom the Business Object Repository (BOR) . Instead, you first label this BAPI as expired andcontinue its support in the release in which you have introduced the new BAPI as well as in thenext functional release. During this time the original BAPI must remain fully functional andexecutable.

The following tasks are required when a BAPI has expired (become obsolete):

•••• Select the relevant SAP business object type in the Business Object Builder and open thenode Methods. Position the cursor on the BAPI and select Edit → Change status to →Obsolete.

•••• In the BOR, document which method(s) are to replace the expiring BAPI.

•••• Record the BAPIs set to “obsolete” in a particular Release in the Note 0107644, “CollectiveNote for Obsolete BAPIs from Release 4.5A”, in the SAPNet - R/3 Frontend.

•••• Inform your users about the relevant successor BAPIs in Release Notes.

The graphic below illustrates the expiry phase of a BAPI. In this example the new BAPI isintroduced into Release 4.0. The replaced BAPI is supported in Release 4.0 (in the correctionrelease in which the new BAPI was introduced) and in the next functional Release “F1”. TheBAPI can then no longer be used in the following functional Release “F2”.

BAPI Programming SAP AG

Incompatible Enhancements

150 December 1999

BAPI Expiry Phase

Release

BAPI

BusinessObject

BAPIBAPI

BusinessObject

BAPIBAPI

Neu

F13.1 4.0 F2

Supported at least until F2

Supported as of 4.0

F = functional Release

Deleting the Replaced BAPIIf the expiry phase of a BAPI set to obsolete has come to an end, you can remove the BAPI fromthe BOR. You should delete an obsolete BAPI as near to the beginning of a new release aspossible, so that developers have time to adjust to its successor.

To delete a BAPI:

•••• Delete the method from the BOR.

To do this display the relevant SAP business object type in the Business Object Builder.Expand the node Methods Place the cursor on the appropriate BAPI and choose Edit →Delete.

•••• Delete the function module that implements the BAPI.

In the Function Builder enter the name of the function module in the Function modulefield and choose Function module → Other functions → Delete.

•••• Record the release in which the BAPI was deleted from the BOR in the Note 0107644,“Collective Note for Obsolete BAPIs from Release 4.5A”, in the SAPNet - R/3 Frontend.

SAP AG BAPI Programming

Customer Modifications and Developments

December 1999 151

Customer Modifications and Developments

PurposeIf required, customers can carry out modifications to existing BAPIs, for example, create newparameters or parameter fields, or develop new BAPIs following this programming guide.

PrerequisitesCustomers and partners who want to create new development objects required in the context ofa modification or own development, should follow the guidelines in the document Changing theSAP Standard [Ext.] as well as “Guidelines for Modifying the SAP Standard in SAPnet.

Also, make sure that the relevant development objects are assigned a name from the customernamespace. For further information see Namespaces [Page 161].

Process FlowModifications to existing BAPIs or the development of customers’ own BAPIs cannot be made forbusiness object types delivered in the standard.

Instead, you create a subtype of the business object type which inherits all the characteristicsand methods of this object type. The original object type becomes the supertype. Then you canmake the modifications/own developments to the derived subtype.

In this way the SAP standard delivered to customers is not changed and the modifications/owndevelopments carried out are retained when the release is upgraded. This procedure alsoenables BAPIs to be modified in steps because further subordinate sub-types of a businessobject type can be created.

For general information about object types and subtype refer to the documentation for SAPBusiness Workflow [Ext.].

The following sections describe how subtypes are created and the two ways of enhancing theBAPIs available for this subtype.

•••• Modifications

Use this way if you want to enhance the functions of an existing BAPI for a subtype. Formore information see Modifying BAPIs [Page 152].

•••• Customer developments

Use this method to provide functionality for the subtype which is not covered by any ofthe existing BAPIs of the subtype nor by any of the BAPIs inherited by the subtype. Forfurther information see BAPI Development [Page 159].

BAPI Programming SAP AG

BAPI Modifications

152 December 1999

BAPI ModificationsPurposeThis section describes the steps involved in modifying an existing BAPI, for example, if newparameters or parameter fields are to be added.

Process FlowBAPI modifications cannot be made to business object types delivered in the standard system.Instead, you have to create a subtype of the business object type and for this subtype you haveto redefine the BAPI method inherited from the superior business object.

Only the redefined BAPI is then available for the subtype; the original inherited BAPI can only becalled from the supertype.

Follow these steps:

1. Create a subtype of the required business object type, as described in Creating Subtypes[Page 160].

2. Redefine the BAPI inherited by the subtype, for example, by adding further parameters ormodifying the implementation of the BAPI. There are several ways to do this, as illustrated inthe example below:

Object type OT has two BAPIs m1 and m2, which are implemented by the functionmodules BAPI_OT_m1 or BAPI_OT_m2:

BAPI_OT_m2

BAPI_OT_m1m1

m2OT

If enhancements to BAPI m2 are required, you can use the following implementationoptions:

Creating a New Function Module for the ImplementationHere a new function module (BAPI_OTsub_m2) is created to call the function module ofthe superior BAPI method (of the supertype). The original functionality is retained andcan be enhanced for customer needs.

The graphic below illustrates the implementation:

SAP AG BAPI Programming

BAPI Modifications

December 1999 153

BAPI_OT_m2

BAPI_OT_m1

m2OT

m2OTsub

m1

BAPI_OTsub_m2

call function . . .

If you use this method, when releases are upgraded, the system checks which interfaceenhancements have been carried out on the original BAPI. For example, if the interfaceof the original BAPI BAPI_OT_m2 is enhanced, the call in BAPI BAPI_OTsub_m2 mustalso be enhanced, if the enhanced functionality of the original BAPI is to be used.

The advantage of using this method is that the original superior BAPI (BAPI_OT_m2),whose stability has been guaranteed, is cleanly encapsulated. Any changes carried outin the future to the original superior BAPI which do not affect the interface or semantics(for example, corrections and optimizations), are automatically copied to the new BAPIwithout requiring the subtype to be changed in any way.

This method is not a good choice, if the encapsulation affects system performancenegatively. This could be the case, if in both BAPI_OT_m2 and in BAPI_OTsub_m2,UPDATE operations are to be made in different fields of the same data record that thedeveloper would like to implement in one single update record (that is with oneUPDATE).

Compatible Modifications to the Superior Function ModuleIn principle, the BAPI method of a subtype can be implemented by the same functionmodule as the method of the suoertype (BAPI_OT_m2 in this example). This is possibleif the modifications of the interface are compatible, for example, if only new optionalparameters have been added (see also SAP Enhancements to Existing BAPIs [Page144]).

The graphic below illustrates the implementation:

BAPI_OT_m2

BAPI_OT_m1

m2OT

m2OTsub

m1

modifiziert

With this implementation method, remember that the modifications must be merged withthe original BAPIs every time a release is upgraded. As of Release 4.5A you can useThe Modification Assistant [Ext.] to do this.

BAPI Programming SAP AG

BAPI Modifications

154 December 1999

The advantage of using this option is that the original code and enhancement can beeasily compared with one another, to achieve, for example, optimal performance ofdatabase UPDATE operations.

The main disadvantage is that the encapsulation achieved by separating the supertypeand subtype for the BAPI definition actually has to be revoked. When changes havebeen made, you must ensure that the function module continues to behave the samewhen the original method of the supertype OT is called. This option can cause problems,if several subtypes of an object type exist in the same system, for example, in the samedevelopment system or for several industry solutions in one system, even though theyhave been created independently of each other, for example for different industrysolutions.

Creating the Implementing Function Module as a Copy of the Superior FunctionModuleHere a copy of the function module of the superior BAPI method is created (in thisexample, BAPI_OT_m2).

The graphic below illustrates the implementation:

BAPI_OT_m1

m2OT

m2OTsub

m1

BAPI_OTsub_m2

modifiziert

BAPI_OT_m2

kopiert

You should only use this option, if the enhancement cannot be done by calling thefunction module of the superior BAPI method.

If global data is defined or form routines are called in the function group associatedwith a BAPI function module, you may have to also copy these data declarations andform routines to ensure the copy of the BAPI can be executed.

Although it is more flexible to modify a copy of the function module, you still have tocheck, with every release upgrade, whether changes have been made to theimplementation of the superior BAPI method. If changes have been made, you have tocopy them to the modified copy. As the origin of the copy is not always supported, werecommend that you do not use this option.

Once you have made the required modification to the copy of the function module,assign it as a method to the relevant business object type in the Business ObjectRepository using the BOR/BAPI Wizard. For further information about the BOR/BAPIWizard see Defining Methods in the BOR Using the BOR/BAPI Wizard [Page 138].

3. When you have made the modification, you have to redefine the modified BAPI of thesubtype in the BOR, as described in Redefining BAPIs [Page 157].

SAP AG BAPI Programming

BAPI Modifications

December 1999 155

4. If redefined BAPIs of a subtype are also to be used when the BAPI is called, you have todefine the delegation relationship between the supertype and subtype. This procedure isdescribed in Defining Delegation Relationships [Page 158].

A delegation relationship is only significant for object-oriented BAPI method calls andnot if the implementing function module is called directly.

For information about delegation see the documentation on SAP Business Workflow [Ext.].

Application Example

The BAPI Material.GetList() for the business object type Material should containadditional parameters. The function module associated with this BAPI isBAPI_MATERIAL_GETLIST.

Customers should first create a sub-type YMaterial of the existing object typeMaterial in the BOR. They will also note that method calls of the business object typeYMaterial for the original object type Material are to be processed, provided that theassociated method is implemented there. This is described as delegation. (For allmethods that are not implemented for the sub-type Ymaterial, the method call isexecuted from the superordinate business object type, Material.)

Customers make the necessary changes in the source code of the function moduleBAPI_MATERIAL_GETLIST, and makes changes to the interface by creating new,optional parameters.

Next, customers create the method GetList() for the sub-type YMaterial using theBOR/BAPI Wizard. The method is linked to the function moduleBAPI_MATERIAL_GETLIST, where the new parameters are included as part of themethod definition.

If, on the other hand, the interface is enhanced with new, mandatory parameters, anew function module must be created and assigned to the methodYMaterial.GetList(). (Customers can also copy the moduleBAPI_MATERIAL_GETLIST, for example, to Y_BAPI_MATERIAL_GETLIST, andthen edit this copy.

At runtime the following process takes place:

– When the BAPI Material.GetList(), the BAPI YMaterial.GetList() is the one actuallyexecuted.

– In the case of all other method calls, the methods of the superordinate businessobject type, Material are executed, because these are not implemented for the sub-type YMaterial.

BAPI Programming SAP AG

Creating Subtypes

156 December 1999

Creating SubtypesTo create a subtype:

1. Choose Tools →=Business Framework → BAPI Development →=Business Object Builder orenter the transaction code SWO1.

2. In the field Object type enter the name of the subtype you want to create and sleet Create.

3. In the next dialog box, enter the required details:

– In the field Supertype enter the name of the object type for which you want to createa subtype.

– In the field Object type enter the name of the subtype you want to create.

Enter appropriate values in the remaining fields.

SAP AG BAPI Programming

Redefining BAPIs

December 1999 157

Redefining BAPIsTo redefine a BAPI of a subtype:

1. Choose Tools →=Business Framework → BAPI Development →=Business Object Builder orenter the transaction code SWO1.

2. Display the subtype just created in the change mode.

3. Place the cursor on the BAPI you want to modify and choose Process →=Redefine.

4. Double-click on the BAPI and select the register ABAP.

5. In the Name field of the modified function module enter and save your information.

BAPI Programming SAP AG

Defining Delegation Relationships

158 December 1999

Defining Delegation Relationships To define the delegation relationship between the supertype and subtype:

1. Choose Tools →=Business Framework → BAPI Development →=Business Object Builderor enter the transaction code SWO1.

2. Choose Settings → Delegate →=System-wide.

3. Switch to the change mode and select New entries.

4. Enter the name of the original object type (supertype) in the field Object type and thename of the subtype in the field Delegation type.

Deactivate the check box GUI-specific.

5. Save your entries.

SAP AG BAPI Programming

BAPI Development

December 1999 159

BAPI DevelopmentPurposeUsing the information in these BAPI Programming guidelines customers and partners can createnew methods for business object types.

Your own developments are carried out in the subtypes derived from business object typesdelivered in the standard and not from the business object types themselves. Use this method toprovide new functionality for the subtype which is not covered by any of the existing BAPIs of thesubtype nor by any of the BAPIs inherited by the subtype.

Process FlowFollow these steps:

1. Create a subtype of the required business object type, as described in CreatingSubtypes [Page 160].

2. Use the guidelines described in this document to create a new BAPI for the subtype andto implement it in its own function module.

The new BAPI can only be used for this subtype and not for the object type from which it wasderived (supertype). All existing BAPIs derived from the supertype can continue to be usedunmodified.

Application Example

Following on from the example in BAPI Modifications [Page 152], an additionalmethod YGetDetail should be created for the sub-type YMaterial of the businessobject type Material. The function module associated with this BAPI isY_BAPI_MATERIAL_GETDETAIL.

Customers should create the new method YGetDetail of the business object typeYMaterial using the BOR/BAPI Wizard. This method is associated with the functionmodule Y_BAPI_MATERIAL_GETDETAIL.

At runtime, when the BAPI Material.YGetDetail is called, the BAPIYMaterial.YGetDetail is actually implemented due to the delegation pointer in thebusiness object type Material.

BAPI Programming SAP AG

Creating Subtypes

160 December 1999

Creating SubtypesTo create a subtype:

1. Choose Tools →=Business Framework → BAPI Development →=Business Object Builder orenter the transaction code SWO1.

2. In the field Object type enter the name of the subtype you want to create and sleet Create.

3. In the next dialog box, enter the required details:

– In the field Supertype enter the name of the object type for which you want to createa subtype.

– In the field Object type enter the name of the subtype you want to create.

Enter appropriate values in the remaining fields.

SAP AG BAPI Programming

Namespaces

December 1999 161

NamespacesDefinitionThe namespace concept describes how customers and partners have to name their developmentobjects to avoid overlapping when SAP software is upgraded.

Customers and partners can create their own development objects, for example, to implement anew BAPI or to modify an existing BAPI. For further information see Customer Modifications andDevelopments [Page 151].

In R/3 Release 3.1 the namespaces Y* and Z* were provided for customers, and the namespaceJ_<number> was reserved for partners.

In R/3 Release 4.0 a new namespace concept was introduced which, together with the longerdevelopment object names, made it easier to assign names to objects developed by customersand partners.

The Business Object Repository (BOR) introduced before R/3 Release 4.0 still uses the oldnamespace concept. For this reason the limitations of the old namespace concept still apply tothe namespaces for BAPI development objects.

Reserved Namespaces/Prefixes for Various Application GroupsUser PrefixSpecial SAP project For example, “JPN” for developments in the Japanese area.

Industrial Business Units (IBUs) do not have specificnamespaces.

Partners/softwarehouses

The following prefixes are used:

•••• J_y" (where "y” is a single digit allocated namespace) forpartners/software houses whose namespaces wereassigned before Release 4.0.

•••• "JJ<Namespace>" (where "<Namespace>" is theregistered namespace) for partners/software houseswhose namespaces were assigned after Release 4.0,for example, JJABC.

Customers "Y" and "Z", for function modules matching "Y_" and "Z_".

If a customer or partner creates a new object type that is not a sub-type of another object type,the naming convention for this object type applies to all the sub-objects. In principle, therefore,SAP object types cannot overlap with each other, regardless of the names of the methods,attributes and so on.

Sub-object types split the namespace for methods, attributes and so on with the superordinateobject type. You must follow the naming conventions for the sub-objects too.

Naming Conventions for BAPI Development ObjectsDevelopment Object Created in... Naming Convention

Domain ABAPDictionary

Standard in the respective R/3 Release

BAPI Programming SAP AG

Namespaces

162 December 1999

Data Element ABAPDictionary

Standard used in the respective R/3 Release

Structure ABAPDictionary

<Prefix>BAPI*

Field in structures ABAPDictionary

-

Append structure ABAPDictionary

Standard used in the respective R/3 Release

Function group FunctionBuilder

Standard used in the respective R/3 Release

Function Module FunctionBuilder

<Prefix>BAPI_<object type>_<method>

Function moduleparameter

FunctionBuilder

<Prefix>*, except for parameters incustomers’ function modules

Object name (name ofobject type)

BOR <Prefix>object name<Suffix>

Suffixes are only used if there is/could be aname conflict within SAP.

•••• If object types from standardapplications require the same objectname, the node of the componenthierarchy is added on as a suffix. Forexample, the business object type,BusinessProcess in Controlling (CO)would be named BusinessProcessCO

•••• If there is a name conflict between astandard application and an IBU, theobject type in the standard isassigned the object name without thesuffix. The object type in the IBU isassigned the IBU code from thecomponent hierarchy as a suffix.

Prefixes are reserved exclusively for partnersand customers. For example, if a customerchanges the object type BusinessProcessCO,a possible name for it could beYBusinessProcessCO.

Object type (technicalobject name)

BOR <Prefix>*

Attribute name BOR <Prefix>*Method BOR <Prefix>*, except for modifications using

delegation, otherwise delegation does notwork.

Method parameters BOR <Function module parameter>

SAP AG BAPI Programming

Namespaces

December 1999 163

BAPI Programming SAP AG

Using BAPIs in Distributed Systems (ALE)

164 December 1999

Using BAPIs in Distributed Systems (ALE)PurposeSince Release 3.0 ALE (Application Link Enabling) technology has enabled data to beexchanged between individual distributed SAP Systems and non-SAP systems.

BAPI Development Even if one of the systems fails, or a communications link is interrupted, theremaining systems must be able to continue to function. Loose coupling means that the individualsystems for the most part communicate asynchronously, (with a time delay) with each other.For these reasons messaging is used for data communication between the participating systemsin ALE distribution scenarios.

As of Release 4.0 you can implement an asynchronous BAPI interface by generating an ALEIDoc interface for the BAPI and using it in an appropriate ALE distribution scenario.

For further information on ALE technology and using BAPIs in the context of ALE, see ALEProgramming Guide [Ext.]. This section provides a general overview of points you should keep inmind when implementing a BAPI to exchange data asynchronously.

Process FlowWhen you use BAPIs for asynchronous messaging, the application in the sending system callsthe generated ALE IDoc interface instead of the BAPI. The ALE IDoc interface performs thefollowing tasks:

•••• Creates an IDoc from the BAPI data

•••• Sends the IDoc to the target system

•••• Receives the IDoc in the target system, creates the BAPI data from the IDoc and calls theBAPI

You can use Transaction BDBG to create the additional objects required for the BAPI in thisprocess, that is, the associated IDoc and the required function modules. This transaction isdescribed in detail in the ALE Programming Guide [Ext.].

PrerequisitesBefore you can implement a BAPI used to transfer data asynchronously in ALE, make sure that aBAPI of this type is actually required for the task in hand. If at least one of the conditions belowapplies, you should implement your BAPI as an asynchronous interface:

•••• Consistent database changes in several systems

Data must be updated consistently on both the local system and on the remote system.

•••• Loose coupling

With a synchronous interface the coupling between the client and the server system istoo narrow. If the connection is interrupted the client system would not be able to functionproperly.

•••• Performance

The interface has a large volume of data or database operations to be carried on theserver system will take a long time. In this situation a synchronous interface cannot beused because performance would be too low.

SAP AG BAPI Programming

Using BAPIs in Distributed Systems (ALE)

December 1999 165

Additional GuidelinesIf you are sure you want to implement your BAPI as an asynchronous interface you should keepin mind the following points in addition to the general BAPI programming guidelines:

•••• The BAPI must not issue a COMMIT WORK command.

•••• The BAPI return parameter must use the reference structure BAPIRET2.

•••• All BAPI export parameters with the exception of the return parameter are ignored and arenot included in the IDoc that is generated.

•••• After the function module which converts the IDoc into the corresponding BAPI in thereceiving system has been called, status records are written for the IDoc in which messagessent in the Return parameter are logged.

If the field type is filled with E (error) or A (abort) in at least one of the transferred returnparameter entries, the status 51 (application document has not been posted) is assignedto all the status records of the IDoc after a ROLLBACK WORK has been executed. If thefield type is filled with E (error) in at least one of the transferred return parameter entries,the status 51 (error, application document has not been posted) is assigned to all thestatus records of the IDoc and a COMMIT WORK is executed. Otherwise status 53(application document posted) is written and a COMMIT WORK executed.

BAPI Programming SAP AG

BAPI Quality Checklist

166 December 1999

BAPI Quality ChecklistDefinitionThe check list below contains extracts from the BAPI Quality Checklist used internally in SAP todevelop BAPIs.

You can refer to this check list during the entire development and implementation of a BAPI.

BAPI Quality ChecklistThis checklist helps you to develop BAPIs in accordance with the programming guidelines andenables you to implement the best quality BAPIs right from the start. You should use thischecklist to manage the development of all BAPIs in your integration scenario.

ScenarioPerson responsible: Developer

BAPIs must be developed as part of an integration scenario. This will ensure that theycomplement each other, and that access to the R/3 functionality is provided in a structured andpractical way.

Scenario to be implemented

[Name of the scenario]

-----------------------------------------------------------------------

Quality of Object Modeling Person responsible: Developer

[] Existing object model

Business object types used in the scenario and person responsible

1. [Name of business object type] [Name of person responsible]

2. [ ] [ ]

3. [ ] [ ]...

BOR methods to be implemented

1. [Name of business object type] [BAPI name]

2. [ ] [ ]

3. [ ] [ ]...

Name of the function module

1. [Name of function module]

2. [ ]

3. [ ]...

----------------------------------------------------------------------

SAP AG BAPI Programming

BAPI Quality Checklist

December 1999 167

SpecificationPerson responsible: Quality assurance/central development department

[ ] BAPI concept or specification has been checked by the central development departmentand by the responsible quality manager.

[Name of the contact person in the central development department]

[Name of the quality manager]

You must mark the checkbox for all the BAPIs in this development request.

----------------------------------------------------------------------

Quality of the Method ConceptPerson responsible: Developer

You must mark the checkbox for all the BAPIs in this development request.

Fields and Parameters

[ ] All field and parameter names must be in English

[ ] All the quantity fields must have units of measurement fields

[ ] All currency amount fields must have currency indicator fields

[ ] All key fields in GetDetail() and GetList() BAPIs must be displayed in a text field.

[ ] All BAPI structures begin with the prefix “BAPI” and all foreign keys are defined.

Data conversion

[ ] Only internal data formats are used, with the following exceptions: (mark these exceptions):

[ ] All the date fields must have the format JJJJMMTT

[ ] All currency amounts are based on the domain BAPICURR

[ ] PSP elements and similar fields use external keys

[ ] Additional fields are provided for ISO codes

[ ] Currency amounts with decimal places are displayed with decimal points in the interface, For example, 10.12 is displayed as 10.12 and not as 1012.

Security issues

[ ] All BAPIs contain authorization checks

[ ] All F4 possible entries have authorization checks

Updates

Database changes can only be made through updates.

Commit Work

BAPIs containing the COMMIT WORK command (exceptions only)

[Name of business object type] [BAPI name]

[ ] [ ]

[ ] [ ]....

BAPI Programming SAP AG

BAPI Quality Checklist

168 December 1999

[ ] No COMMIT WORK in asynchronous BAPIs that are sued in the context of ALE/BAPIIntegration

----------------------------------------------------------------------

Quality of the BOR DefinitionPerson responsible: Developer

[ ] Table parameters are marked in the BOR "Imp. and Exp." only if they have to be imported aswell as exported. Otherwise either the indicator Imp or Exp is used.

Person responsible: Central development department

[ ] Instance-dependency/instance-independency checked

[ ] BAPI name(n) OK (agree name with person in development department)

[Name of person]

A cross in a checkbox applies to all the BAPIs in this development request.

------------------------------------------------------------------------

Quality of Documentation and FunctionalityPerson responsible: QM

A cross in a checkbox applies to all the BAPIs in this development request.

Documentation

[ ] BAPIs and all the associated parameters are fully documented

[ ] Documentation on the parameter RETURN contains all the important return codes andmessages

[ ] The comprehensibility and user friendliness of the documentation has been checked

[ ] Documentation describes the use of the COMMIT WORK command (if applicable)

[ ] Documentation on the function module has been saved to the active version

[ ] Business object type has been documented

[ ] BAPI scenario (ALE Business Process) has been documented

Tests

[ ] Individual tests OK

[ ] Integration tests OK

[ ] Calling from external programs OK

[Name of quality manager responsible]

------------------------------------------------------------------------

SAP AG BAPI Programming

BAPI Quality Checklist

December 1999 169

Authorization to ReleasePerson responsible: Quality assurance/central development department

[ ] Authorized by member of central development department

[Name of person]

[ ] Authorized by quality manager

[Name of the quality manager]

A cross in a checkbox applies to all the BAPIs in this development request.

------------------------------------------------------------------------If all the fields have been marked are filled, you can release your BAPI(s) and the developmentrequest. Thank you for your cooperation.