Vous êtes sur la page 1sur 45

SAP NetWeaver How-To Guide

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Applicable Releases: SAP NetWeaver Gateway 2.0 SP03

Version 2.0 February 2012

Copyright 2012 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation. IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix, i5/OS, POWER, POWER5, OpenPower and PowerPC are trademarks or registered trademarks of IBM Corporation. Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems Incorporated in the United States and/or other countries. Oracle is a registered trademark of Oracle Corporation. UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered trademarks of Citrix Systems, Inc. HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology. Java is a registered trademark of Sun Microsystems, Inc. JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape. MaxDB is a trademark of MySQL AB, Sweden. SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP NetWeaver, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies. Data contained in this document serves informational purposes only. National product specifications may vary.

These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies ("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing herein should be construed as constituting an additional warranty. These materials are provided as is without a warranty of any kind, either express or implied, including but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP shall not be liable for damages of any kind including without limitation direct, special, indirect, or consequential damages that may result from the use of these materials. SAP does not warrant the accuracy or completeness of the information, text, graphics, links or other items contained within these materials. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third party web pages nor provide any warranty whatsoever relating to third party web pages. SAP NetWeaver How-to Guides are intended to simplify the product implementation. While specific product features and procedures typically are explained in a practical business context, it is not implied that those features and procedures are the only approach in solving a specific business problem using SAP NetWeaver. Should you wish to receive additional information, clarification or support, please refer to SAP Consulting. Any software coding and/or code lines / strings (Code) included in this documentation are only examples and are not intended to be used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent. Disclaimer Some components of this product are based on Java. Any code change in these components may cause unpredictable and severe malfunctions and is therefore expressively prohibited, as is any decompilation of these components. Any Java Source Code delivered with this product is only to be used by SAPs Support Services and may not be modified or altered in any way.

Document History
Document Version 1.00 2.00 Description First official release of this guide Updated to reflect changes introduced in SP03

Typographic Conventions
Type Style Example Text Description Words or characters quoted from the screen. These include field names, screen titles, pushbuttons labels, menu names, menu paths, and menu options. Cross-references to other documentation Example text Emphasized words or phrases in body text, graphic titles, and table titles File and directory names and their paths, messages, names of variables and parameters, source text, and names of installation, upgrade and database tools. User entry texts. These are words or characters that you enter in the system exactly as they appear in the documentation. Variable user entry. Angle brackets indicate that you replace these words and characters with appropriate entries to make entries in the system. Keys on the keyboard, for example, F2 or ENTER.

Icons
Icon Description Caution Note or Important Example Recommendation or Tip

Example text

Example text

<Example text>

EXAMPLE TEXT

Table of Contents
1. 2. 3. 4. Business Scenario............................................................................................................... 1 Background Information ..................................................................................................... 1 Prerequisites ........................................................................................................................ 1 Step-by-Step Procedure ...................................................................................................... 3 4.1 4.2 4.3 4.4 4.5 Create the Data Model based on RFC Data Sources .................................................. 3 Map the QUERY Operation .......................................................................................... 6 Map the READ Operation ........................................................................................... 13 Create a Consumption Model ..................................................................................... 18 Test the QUERY and READ Operations .................................................................... 19 4.5.1 4.5.2 4.5.3 4.5.4 4.6 4.7 4.8 4.9 View the Metadata ......................................................................................... 20 Configure a System Alias for the Service ...................................................... 21 Test the QUERY Operation ........................................................................... 22 Test the READ Operation .............................................................................. 26

Map the CREATE Operation ...................................................................................... 27 Map the UPDATE Operation ...................................................................................... 30 Map the DELETE Operation ....................................................................................... 32 Test the CREATE, UPDATE, and DELETE Operations............................................. 33 4.9.1 4.9.2 4.9.3 Test the CREATE Operation.......................................................................... 33 Test the UPDATE Operation.......................................................................... 36 Test the DELETE Operation .......................................................................... 37

5.

Summary ............................................................................................................................ 39

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

1.

Business Scenario

Maintaining users in a SAP system is one of the most common tasks for SAP system administrators. In fact, transaction SU01 is one of the most actively used transactions among all SAP customers. Many Business APIs (BAPIs) for the User object are available on any SAP NetWeaver ABAP AS system which includes all the SAP Business Suite applications. With SAP NetWeaver Gateway, these BAPIs can be leveraged as data sources so that simplified REST based services can be called to maintain business entities from virtually any device or client application which could make tasks, such as user maintenance, easier for SAP administrators. This How-To Guide provides the details on how to create and test a SAP NetWeaver Gateway service based on the User related BAPIs. As a result, CRUD (CREATE, READ, UPDATE, and DELETE) operations can be executed using the Gateway service to maintain users in a SAP system. The User example can then be extended for other business entities with similar associated BAPIs in a SAP application.

2.

Background Information

SAP NetWeaver Gateway provides the capability to generate content automatically without the need to write any code. A Gateway specific design time tool is offered in the ABAP Development Workbench (transaction SE80) to create Gateway Data Models to design and maintain the content of the service based on existing data sources, such as Remote Function Calls (RFCs), Screen Scraping, and Business Object Repository (BOR) objects. A Consumption Model is then created to expose the content to be consumed as an OData service adhering to REST (Representational State Transfer) based principles. Information in this document details this approach of creating the appropriate data model and generating all the necessary model and runtime code. New in SP03 is the ability to generate the code based on the OData channel. This is not to be confused with the OData Channel approach, which is another means of building and exposing SAP content offered by SAP NetWeaver Gateway that provides developers more control and flexibility. Although this approach is not covered in this guide, detailed coverage of this topic is available in other How-To Guides on the SAP Community Network (SCN). For more information on these topics, refer to the following: SAP NetWeaver Gateway Developer Guide SAP NetWeaver Gateway Page on SCN SAP NetWeaver Gateway How-To Guides on SCN

More information on OData can be found at http://www.odata.org.

3.

Prerequisites
Access to a configured SAP NetWeaver Gateway 2.0 SP02 system Proper permissions in the system (Gateway and SAP backend system). If the User objects are in another SAP backend system, you need valid connection configuration from Gateway to that backend

The following are the prerequisites to complete the steps in this guide:

Firefox and the Firefox REST add-on for testing.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Other REST clients (e.g. WFetch) can be used as well, but the instructions in this guide are specifically for the Firefox REST client. Familiarize yourself with the specific BAPI you want to use. Refer to the function module documentation for the specific BAPI in transaction SE37. If you are using Internet Explorer to test the QUERY and READ operations as specified in this guide, make sure it is not configured to show friendly error messages. To configure, go to Tools Internet Options Advanced Uncheck Show friendly HTTP error messages. This will help you analyze an y errors if they occur. Additional Information SAP NetWeaver Gateway on SAP Help Portal SAP NetWeaver Gateway Page on SCN Note 1574568 - SAP NetWeaver Gateway 2.0 - Known Constraints

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.

Step-by-Step Procedure

The following steps guide you through the process of creating and testing a Gateway service based on BAPIs of the User object. Given that the SAP User object BAPIs are available in any SAP NetWeaver AS ABAP based systems, this exercise can be done based on User data that exists locally on the SAP NetWeaver Gateway system or user data that resides on a backend SAP Business Suite system.

4.1

Create the Data Model based on RFC Data Sources

The Gateway Data Model you create contains the operations you want to perform at runtime, mapped to specified data and attributes. At runtime, this Data Model is exposed to SAP NetWeaver Gateway services that invoke the operations that you defined at design time, returning data to the end user.
...

1. Log on to the Gateway system and go to the ABAP Development Workbench transaction SE80. 2. In the Object Navigator, choose the object type GW Data Model from the drop down.

3. Enter Z_USER_RFC_<XX> as the name of the Data Model and click on the Display (eye glasses) button. Replace <XX> with some unique identifier (e.g. your initials or student number).

4. If prompted to find the model, just click

to continue.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

5. Select Yes when prompted to create the data model object.

6. In the Create Data Model dialog, press F4 in Type and select PS (for Public Solution model) as the data model type, and then select Generate from Data Source Object. Click to continue.

7. Enter a Description, and in Data Source Type select 2 Remote Function Calls".

8. In System Alias, press F4 and choose a system alias according to where the User object data resides locally or in another backend system. In this example, the backend is IDD_800. 9. Click Continue.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

10. Specify a package to which your objects can be saved for transport purposes. Select an appropriate package or select Local Object to save as local objects that will not be transported.

11. You should now be navigated to the Create Data Model screen where the actual Gateway data modeling process takes place.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.2

Map the QUERY Operation

The QUERY operation is used to get a list of the business objects that your Gateway Service is mapped to. In this step you will create the QUERY operation based on the BAPI_USER_GETLIST remote function module.
...

1. From the Create Data Model screen, click on the Search button

2. Enter BAPI_USER* to get a list of the User object related BAPIs.

3. Select BAPI_USER_GETLIST from the list.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4. On the right side, select the Create Mapping button.

5. Choose Query for the operation type.

Now we will map specific fields from the BAPI to our Query operation. First, we can set a constant value for MAX_ROWS. 6. Right-click on MAX_ROWS to highlight it (left-clicking will uncheck the attribute!). Then select the Set Constant Value button.

Note BAPIs and RFCs that supply a MAX_ROWS or similar import parameter also allow for an option to limit the number of items returned from the consumption side at runtime. To do so, the client can include the $top query string parameter according OData specifications (e.g. $top=5). If a constant is set for MAX_ROWS and the $top parameter is also provided, the value for the $top parameter will take precedence. For example, in order to prevent huge query results from being returned, a constant value can be set for MAX_ROWS (e.g. set to 100). If a larger result set is required, the $top parameter can be specified in the request. 7. Set the value to '100' (include the single quotes!) and click to continue.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

8. Next set another constant of 'X' for attribute WITH_USERNAME.

Setting this attribute with the constant results in the inclusion of the name field values (i.e. FIRSTNAME, LASTNAME, FULLNAME) in the query results. Afterwards, the mapping should appear as follows:

9. Uncheck nodes RETURN and SELECTION_EXP. Now your mapping should look like this:

10. Click

to continue and close the mapping window.

A key field must be set for the data model and each operation must use the same key field(s). In this case, USERNAME will serve as the key property. 11. Back in the main data model screen, to set USERNAME as the key property, right-click on USERNAME and select Set Key.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

As a result, USERNAME now has a key icon next to it.

Note Prior to SP03, we had to use S_COR_ID-VALUE as the primary key of generated Gateway services. However, now with the OData channel option now available for data source generation, the use of S_COR_ID-VALUE is no longer necessary. We also want to add a couple of properties to our Gateway data model to leverage the use of SAP range tables when querying for user data. This basically allows for additional filtering capabilities or selection critieria when searching for particular users in the system. 12. Right-click on root node Z_USER_RFC_<XX> and select Add Property.

13. Create the new attribute called USERID of type Edm.string with an appropriate label as follows:

14. Click Continue.

February 2012

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

15. Add another property called ISLOCKED of type Edm.string with an appropriate label as follows:

16. Click Continue. Now you should see both new attributes in the data model.

Now we want to adjust the Query mapping to take advantage of the supplied range table in the BAPI. 17. Highlight the QUERY operation and click on the Change Mapping button.

February 2012

10

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

18. Make sure the SELECTION_RANGE node is checked. Highlight it and click on the Set Range Table button.

19. In the Map Range Table window, click on Add. 20. Select USERID and click to continue.

21. Back in the Map Range Table window, delete the value P from the Semantic column for the PARAMETER attribute (you will have to place the cursor in the field and delete it manually) and set a constant value of 'USERNAME' (include the single quotes!).

February 2012

11

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

22. Add two more range table parameters one with a mapping route through the ISLOCKED attribute and another through the LASTNAME attribute. Note that you will have to double-click into each mapping route parameter to set the respective range table attribute. For ISLOCKED, set the range table attributes as follows:

For LASTNAME, set the range table attributes as follows:

Note The permitted range table values for the PARAMETER and FIELD attributes can be found in the function module documentation for BAPI_USER_GETLIST in transaction SE37.

February 2012

12

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

23. Click on to close the Map Range Table window and again to close the Map Operation window. You should now be back in the Create Data Model main screen. 24. Now it is time to generate your data model. Click on the Generate button near the top left corner.

Note There is no option to save your data model. In order to save your work, you must generate it. Also, you will need to be a registered developer in your system to be able to generate successfully. 25. Upon successful generation, you should see the following:

_USERNAM E includes the name of the us er in the r

4.3

Map the READ Operation

The READ operation is used to get the details of a particular business object that your Gateway Service is mapped to. In this step you will create the READ operation based on the BAPI_USER_GET_DETAIL remote function module. 1. In the list of User BAPIs, find and select BAPI_USER_GET_DETAIL.

2. With the BAPI highlighted, click on the Create Mapping button. 3. Select the Operation Type to Read. Note You will notice that the function module BAPI_USER_GET_DETAIL is rather complex, containing a large number of structure and table parameters. One of the significant benefits of Gateway is the capability to adapt and simplify such complex SAP interfaces so that external clients can more easily consume SAP business data. In the following steps, this complex BAPI will be greatly simplified for easier consumption. 4. Since there are many more data nodes that will not be used, it will be easier to deselect everything and then reselect the ones we will use. Uncheck the root node BAPI_USER_GET_DETAIL.

February 2012

13

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

You will receive the following warning, but thats ok. Click Yes to continue.

5. Now click on the Collapse All button.

6. For now, only check the nodes CACHE_RESULTS, USERNAME, ACTIVITYGROUPS, and PROFILES.

7. Expand the ADDRESS node and check attribute TITLE_P (do not check the ADDRESS node itself this will be done automatically). Then click the Change Mapping Route button.

February 2012

14

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

8. Map TITLE_P to the root node by highlighting the root node and changing the property name to TITLE.

9. Click on

to continue. Results so far should appear as follows:

10. Check FIRSTNAME, LASTNAME, and FULLNAME.

As you can see, these are matched and mapped automatically to existing properties under the root node in the data model. They exist due to the work done previously for the QUERY operation. We want to flatten the remaining ADDRESS attributes by changing the mapping routes so that they fall under the root node and not within the ADDRESS node. 11. Select the following attributes and change the mapping route to so that it is directly under the root node. Also, rename them to the mapping route value as specified in the table below in bold (Hint: Look at the TITLE_P example a few steps back). Attribute LANGU_P DEPARMENT COMM_TYPE NAME CITY Mapping Route LANGUAGE DEPARMENT COMM_TYPE NAME CITY

February 2012

15

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

COUNTRY REGION TEL1_NUMBR E_MAIL

COUNTRY REGION TELEPHONE E_MAIL

12. The final result for the ADDRESS node should look as follows:

February 2012

16

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

13. Expand the ACTIVITYGROUPS and PROFILES nodes and rename and set their properties as shown below. Notice that they are renamed but are kept under their respective nodes (i.e. do not map them to the root node).

14. Click on

to close the Map Operation window.

15. Within the data model section on the lower right, scroll to the bottom to find the ACTIVITYGROUPS and PROFILES object nodes with cardinality 0..n.

A key has to be set for objects with a 0..n cardinality. 16. Expand ACTIVITYGROUPS, right-click on ROLE and choose Set Key.

17. Do the same for PROFILES by setting PROFILE as key.

February 2012

17

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

18. Generate your data model. You should see success messages in the generation log.

4.4

Create a Consumption Model

Now that some of the data model has been created, the associated content is ready to be exposed to the outside world and consumed as an OData service adhering to REST based principles. This is done by creating a Consumption Model. Once a consumption model is created, the Gateway service is exposed via the Internet Communication Framework (ICF).
...

1. Proceed to the ABAP Development Workbench (transaction SE80). Tip If you are currently in the data modeling tool, you can navigate back to SE80 using the Object Navigator button.

2. Expand node Z_USER_RFC_XX_0001_PS if necessary. Right-click on Related GW Consumption Models and select Add Consumpt. Model.

Tip Here we are creating the consumption model by adding it to an existing data model. For future reference, it is also possible to initiate the creation of a consumption model on its own by selecting object type GW Consumption Model.

February 2012

18

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

3. For the Identifier, enter z_user_rfc_<XX> (it will automatically convert to upper case) and click on to continue.

4. Select Yes to confirm the creation of the consumption model.

5. Enter a description and click

to continue.

6. Save the object to a package or as a local object (package $TMP).

4.5

Test the QUERY and READ Operations

In order to test the service operations, a simple HTTP client tool is required. In this guide, Firefox (with REST add-on) will be used as an example, but there are other tools available such as WFetch from

February 2012

19

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Microsoft. Either of these can be downloaded for free. The following steps assume that have the Firefox browser and have installed the REST Client add-on.

4.5.1

View the Metadata

When the data model is created, you can get a good description of the resulting service and its data format by looking at the service metadata. This can be done after the consumption model is created. 1. Expand the Related GW Consumption Models node and double-click on your consumption model Z_USER_RFC_XX_0001.

2. To view the metadata, click on the Metadata button.

This launches the default browser and displays the service metadata document in EDMX format. It also describes the service in Entity Data Model terms according to OData specifications. More information on OData can be found at http://www.odata.org.

February 2012

20

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Note The XML button will also launch a browser window and display whats called the Service Document. The service document is the entry point for an OData service and provides information on all the collections of resources available and the relative links to the resources. For a detailed breakdown of the Service Document and Service Metadata document, refer to How To Write an OData Channel Gateway Service. Part 1 - The Model Provider Class. Note Notice the string Z_USER_RFC_XX in the URL. http://<GatewayHost>:<port>/sap/opu/odata/sap/Z_USER_RFC_XX/ $metadata This is the service name that was specified when creating the consumption model. Also take note of the $metadata string needed to access the service metadata document.

4.5.2
...

Configure a System Alias for the Service

Starting with SP03, a system alias must be configured for OData channel based data models to identify which backend system will process the OData. 1. Using transaction SPRO, select SAP Reference IMG and navigate to SAP Customizing Implementation Guide SAP NetWeaver Gateway OData Channel Administration General Settings Assign SAP System Aliases to OData Service

February 2012

21

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

2. Choose New Entries.

3. Under Service Doc. Identifier, enter the name of your data model Z_USER_RFC_XX_0001. For SAP System Alias, use F4 to select the appropriate backend alias for this service. For example, IDD_800. You can press <Enter> to validate your entries.

Since theres only one entry right now, the default system checkbox can be checked or left blank. 4. Save your system alias configuration.

4.5.3

Test the QUERY Operation

Actual testing of the Gateway service can start with the Query operation. The Query operation can potentially return large sets of data. To address this, Gateway provides mechanisms to restrict the number of results as well as the capability to filter query results according to mapped selection criteria.

Executing the Main Query Operation


To execute the Query operation, lets use the Firefox REST client.
...

1. Open up the Firefox REST client (you can find it under the Firefox Tools menu).

February 2012

22

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

2. The Query operation URL is similar to the URL used to get the metadata. In the URL, replace the string $metadata with z_user_rfc_<xx>Collection. So the complete URL would be: http://<GatewayHost>:<port>/sap/opu/odata/sap/Z_USER_RFC_XX/ z_user_rfc_<xx>Collection 3. User credentials can be supplied in advanced by pressing the Login button be supplied when prompted at execution time. 4. Using the Query operation URL, set the Method to GET and select Send. or can

Results are at the bottom. The Response Header should show an HTTP status code of 200.

In the Formatted XML tab, you should be able to see a number of user entries returned from the query.

February 2012

23

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Notice that only the firstname, lastname, and fullname properties hold values. Thats mainly because function module BAPI_USER_GETLIST is not designed to return detailed user data. That is reserved for BAPI_USER_GET_DETAIL. Of course how the service is mapped in the data model also usually plays a major role on what data is returned just not in this case. Also, there should be a maximum of 100 user entries returned by default. Remember that the property MAX_ROWS was set to a constant value of '100'.

Restricting Results with $top


Now lets limit the number of user entries returned by using the $top parameter. Add $top=5 to the end of the URL as a query parameter by first appending a '?' and then adding the parameter: /Z_USER_RFC_XX/z_user_rfc_<xx>Collection?$top=5

After clicking on Send, there should be no more than 5 entries returned. Note Remember that $top takes precedence over the constant set for MAX_ROWS. If more than 100 results are needed, $top can be used.

Target Queries using $filter and Mapped Range Tables


Since there is potentially a large user base, besides limiting with $top, it would be helpful to filter the returned data using available selection criteria. This is where we can take advantage of the range table mapped for the Query operation.

February 2012

24

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

Specific User To find a specific user, modify the URL as follows: /Z_USER_RFC_XX/z_user_rfc_<xx>Collection?$filter=userid eq '<UserID>' Example http://mygwserver:8000/sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc_xxC ollection?$filter=userid eq 'SMITH'

This returns one result an entry for user Danny Smith. Locked or Unlocked Users If you wanted to only look for users that are locked, the following filter can be user: ?$filter=islocked ne '0' For only unlocked users: ?$filter=islocked eq '0' Other Filters ?$filter=lastname eq 'SMITH' ?$filter=substringof(lastname,'SM') ?$filter=substringof(lastname,'SM') and islocked ne '0' Note Although OData specifications for the $filter option include a large variety of logical and arithmetic operators along with various String functions, Gateway does not currently support all of them today. You can get the latest on the supported filter options by checking Note 1574568 - SAP NetWeaver Gateway 2.0 - Known Constraints. Users with LASTNAME equal to SMITH Users with LASTNAME containing SM Users with LASTNAME containing SM and that are also locked

February 2012

25

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.5.4

Test the READ Operation

Returned in the Query operation for each entry is a set of links that allows for easy access to subsequent data in this case, the details for each user. For example, for our user Danny Smith, the following links are provided:

In particular, look for the href attribute value provided. These are relative links that can be plugged into the URL of the service to access the data mapped by our READ operation. The top href link performs the main READ operation and gets the data mapped to the root node (e.g. our address data). The other two href links correspond to the ACTIVITYGROUPS and PROFILES nodes that we did not flatten in our mapping and have a cardinality of 0..n. 1. To execute the READ operation, for any entry (i.e. enclosed within <atom:entry> tags), plug in the top href link provided by replacing z_user_rfc_<xx>Collection with the href value. For example, in the Danny Smith entry: /sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc_xxCollection(value='SMITH ') Delete any $filter options if present.

February 2012

26

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

2. To read the ACTIVITYGROUPS or PROFILES data, you can do the same thing. Copy the href link for one of these and replace z_user_rfc_<xx>Collection with the href value. For example, in the Danny Smith entry, to retrieve the ACTIVITYGROUPS data: /sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc_xxCollection('SMITH')/act ivitygroups_r

4.6

Map the CREATE Operation

The CREATE operation is used to create a business entity. In order for Gateway to support the CREATE operation via the Generic Channel, the structure of the business object mapping must be completely flat. No structures or tables are allowed to be passed as input. Starting with Gateway 2.0/SP02, via the OData Channel, deep insert functionality is possible, allowing the creation of business entities using structures or tables. Please refer to the SAP Online Help portal for more information on Deep Insert functionality. In this step you will map the CREATE operation to the BAPI_USER_CREATE1 remote function module.
...

1. In transaction SE80, access your Gateway data model object (you may need to enter it as Z_USER_RFC_<XX>_0001_PS). 2. Once displayed, double-click on the root object Z_USER_RFC_<XX>_0001_PS.

3. Navigate to the Gateway data modeling tool by clicking on the Open generator icon.

4. Click on the Display <> Change icon to go into edit mode.

5. Click on the Search button and get a list of BAPI_USER* function modules and highlight BAPI_USER_CREATE1.

February 2012

27

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

6. Click on the Create Mapping button.

7. In the Map Operation window, choose Create. 8. As done for the READ operation, uncheck root node BAPI_USER_CREATE1, confirm the warning, and collapse the structure.

9. Check the PASSWORD node and the USERNAME attribute. 10. Expand the PASSWORD node and rename the property name BAPIPWD to PASSWORD.

February 2012

28

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

11. Expand the ADDRESS node without checking it. Map the address attributes as shown below, renaming and mapping to the root node where necessary. Note that many of these fields (e.g. DEPARTMENT) already exist and simply have to be selected in the Change Mapping Route window.

12. Leave everything else unchecked and close the Map Operation window. 13. Generate the data model.

February 2012

29

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.7

Map the UPDATE Operation

The UPDATE operation updates a business entity. Just like with the CREATE operation, in order for Gateway to support the UPDATE operation the structure of the business object mapping must be completely flat. No structures or tables are allowed to be passed as input. In this step you will map the UPDATE operation to the BAPI_USER_CHANGE remote function module.

1. Highlight BAPI_USER_CHANGE.

2. Click on the Create Mapping button.

3. In the Map Operation window, choose Update. 4. As done for the CREATE operation, uncheck root node BAPI_USER_CHANGE, confirm the warning, and collapse the structure.

February 2012

30

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

5. Check the PASSWORD node and the USERNAME attribute. Notice that PASSWORDX gets checked automatically when PASSWORD is checked. 6. Expand the PASSWORD node and rename the property name BAPIPWD to PASSWORD and map it to the root node if necessary.

7. Expand the ADDRESS node without checking it. Map the address attributes as follows, renaming and mapping to the root node where necessary:

All corresponding attributes in ADDRESSX and PASSWORDX will be set to a constant value of 'X' automatically. 8. Leave everything else unchecked and close the Map Operation window. 9. Generate the data model.

February 2012

31

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.8

Map the DELETE Operation

The DELETE operation deletes a business entity. Many SAP interfaces do not provide a direct delete operation given the risk of losing potentially critical business data. If they do, sometimes it is only to mark the object for deletion instead of completely wiping out the business object. However, for some objects, such as the User object, a direct delete function module is available. In this step you will map the DELETE operation to the BAPI_USER_DELETE remote function module.
...

1. Highlight BAPI_USER_DELETE.

2. Click on the Create Mapping button. 3. In the Map Operation window, choose Delete. 4. Uncheck the RETURN node.

5. Close the Map Operation window. Now you should see all the CRUD (Create, Read, Update, and Delete) operations along with the Query operation included in the data model.

6. Generate the data model.

February 2012

32

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

4.9

Test the CREATE, UPDATE, and DELETE Operations

Starting with Gateway 2.0/SP03, Cross-Site Request Forgery (CSRF) protection using token exchange and validation is enabled by default for all data modifying requests (e.g. Create, Update, Delete). This means that a valid CSRF token must first be retrieved using a non-modifying request (e.g. using the GET method). Then it can be sent along with the subsequent modifying request and validated before normal processing continues. For more information on CSRF protection mechanisms in SAP NetWeaver Gateway, please visit the SAP Help Portal: Cross-Site Request Forgery Protection.

4.9.1

Test the CREATE Operation

A CREATE operation uses the HTTP POST method and is called against the same URL as the QUERY operation.

Retrieve the CSRF Token First


...

1. Open the Firefox REST client. 2. Set the method to GET. 3. Set the URL to the same one used for the QUERY operation: Example http://mygwserver:8000/sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc _xxCollection 4. Click the Add Request Header button and add the HTTP header X-CSRF-Token with a value of Fetch as shown:

5. From the Firefox main menu, choose Tools Web Developer be able to copy the token from the Firefox window.

Web Console so that you will

6. User credentials can be supplied in advanced by pressing the Login button be supplied when prompted at execution time. 7. Click on the Send button to execute the query.

or can

8. On the Web Console at the top, click on the link that appears corresponding to the request just executed.

February 2012

33

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

9. In the pop-up window, scroll to Response Headers at the bottom and copy the token value returned.

Close the pop-up window.

Execute the Create Operation


...

1. Set the method to POST and change the value for header X-CSRF-Token to the token value that was retrieved in the previous step (Hint: Just double-click on Fetch to edit the value). 2. Add a new HTTP header called Content-Type with value application/atom+xml and keep the URL set to the Query URL.

Next you need to supply the actual data that will be used to create the user. The XML format used is basically in the form of an <atom:entry> which youve already seen when calling a READ operation. Main difference is that youll only need to supply the data that is mapped in the data model for the CREATE operation. A sample XML dataset is provided below. 3. Copy the sample XML below to the Request Body of the Firefox REST client. <?xml version="1.0" encoding="utf-8" standalone="yes"?> <atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/meta data"> <atom:content type="application/xml"> <m:properties> <d:username>TEST_GW1</d:username> <d:password>initial</d:password> <d:title>Mr.</d:title> <d:firstname>Joe</d:firstname> <d:lastname>Smith</d:lastname> <d:language>E</d:language> <d:department>Sales</d:department> <d:comm_type>INT</d:comm_type> <d:telephone>111-222-3333</d:telephone> <d:e_mail>j.smith@xyzcorp.com</d:e_mail> <d:city m:null="true" /> <d:country m:null="true" /> <d:fullname m:null="true" /> <d:islocked m:null="true" /> <d:userid m:null="true" /> <d:name m:null="true" /> <d:region m:null="true" />

February 2012

34

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

</m:properties> </atom:content> </atom:entry> Note Even though every field in your Gateway data model may not be relevant for the CREATE operation, they must be supplied in the request with either a valid value or with its null attribute set to true. For example, in the sample above, the property city is not needed for the CREATE operation, but it still must be included with its null attribute set to true ( <d:city m:null=true /> ). Otherwise, a HTTP 500 error can result with error message The Data Services Request could not be understood due to malformed syntax. 4. Now that the request is ready, click on the Send button.

5. Upon successful creation, you should receive an HTTP Status Code: 201 Created in the Response Header.

An OData standard is that after every CREATE operation has completed, the client should automatically perform a READ operation. In the Response Header section, look at the Location parameter in the HTTP header returned to the client. This is the URL to perform the READ operation.

February 2012

35

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

6. Now select the Formatted XML tab. In this section, you see the resulting XML returned after the client has performed the automatic READ.

4.9.2

Test the UPDATE Operation

An UPDATE operation uses the HTTP PUT method and is called against the same URL as the READ operation. 1. Change the method to PUT in the Firefox REST client. 2. The URL should be set to the same one used for the READ operation. For example: http://mygwserver:8000/sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc_ xxCollection('TEST_GW1') 3. Make sure the HTTP headers X-CSRF-Token and Content-Type are set.

You should be able to use the same token used for the CREATE operation earlier. 4. The same XML request body can be used as the one used for the CREATE operation. <?xml version="1.0" encoding="utf-8" standalone="yes"?> <atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/meta data"> <atom:content type="application/xml"> <m:properties> <d:username>TEST_GW1</d:username> <d:password>initial</d:password> <d:title>Mr.</d:title> <d:firstname>Joseph</d:firstname> <d:lastname>Smith</d:lastname> <d:language>E</d:language> <d:department>Sales</d:department> <d:comm_type>INT</d:comm_type> <d:telephone>111-222-3333</d:telephone> <d:e_mail>j.smith@xyzcorp.com</d:e_mail> <d:city m:null="true" /> <d:country m:null="true" /> <d:fullname m:null="true" /> <d:islocked m:null="true" /> <d:userid m:null="true" /> <d:name m:null="true" /> <d:region m:null="true" /> </m:properties> </atom:content> </atom:entry>

February 2012

36

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

5. Change a field for testing (e.g. changing firstname from Joe to Joseph) and click on Send.

6. Upon successful update, you should receive an HTTP Status Code: 204 No Content. This means the update succeeded but as implied by the status text, there is no response body returned.

Tip To perform a quick verification of the update, simply change the HTTP method to GET and Send. This performs a READ of the same object and you can verify the results in the Response Body or Formatted XML tab.

4.9.3

Test the DELETE Operation

A DELETE operation uses the HTTP DELETE method and is also called against the same URL as the READ (or UPDATE) operation. No request body is needed for the DELETE operation. 1. Change the method to DELETE in the Firefox REST client. 2. The URL should be set to the same one used for the READ (or UPDATE) operation. For example: http://mygwserver:8000/sap/opu/odata/sap/Z_USER_RFC_XX/z_user_rfc_ xxCollection('TEST_GW1')

February 2012

37

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

3. Make sure the HTTP headers X-CSRF-Token and Content-Type are set.

You should be able to use the same token used for the CREATE/UPDATE operation earlier. 4. Clear the request body if necessary. For a DELETE operation, a request body is not necessary as the object to delete is identified from the key fields in the URL. 5. Click the Send button in your Firefox REST client.

6. Similar to an UPDATE operation, upon successful deletion you should receive an HTTP Status Code: 204 No Content.

7. You can verify by executing a GET against the same URL. In the Response Header tab, the result shows a HTTP 400 Bad Request.

In the Formatted XML tab, the error message shows that user does not exist which confirms the user was deleted.

February 2012

38

How To... Create a Gateway Service Using the RFC Generator - Advanced Scenario

5.

Summary

Without having to write a single line of code, SAP NetWeaver Gateway allows SAP customers to create and expose REST compliant services enabling the ability to search for and maintain business entities in an SAP system. Existing resources (e.g. BOR objects and corresponding RFCs/BAPIS) can be leveraged as data sources in order to minimize any potential disruption on the backend as consumers look for new and innovative ways to access SAP data In the previous steps, a Gateway service that allows for all the CRUD (CREATE, READ, UPDATE, and DELETE) operations was quickly modeled, simplified, and exposed to allow client applications to more easily consume and maintain SAP business data. This guide covered the approach of creating an appropriate data model and generating all the necessary model and runtime code. Starting with 2.0/SP03 is the ability to generate the code based on the OData channel.

February 2012

39

www.sdn.sap.com/irj/sdn/howtoguides

Vous aimerez peut-être aussi