using the rest adapter - oraclethe rest adapter provides the following capabilities when exposing an...

87
Oracle® Cloud Using the REST Adapter Release 18.3 E66630-19 September 2018

Upload: others

Post on 10-Feb-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

  • Oracle® CloudUsing the REST Adapter

    Release 18.3E66630-19September 2018

  • Oracle Cloud Using the REST Adapter, Release 18.3

    E66630-19

    Copyright © 2015, 2018, Oracle and/or its affiliates. All rights reserved.

    Primary Author: Mark Kennedy

    This software and related documentation are provided under a license agreement containing restrictions onuse and disclosure and are protected by intellectual property laws. Except as expressly permitted in yourlicense agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify,license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means.Reverse engineering, disassembly, or decompilation of this software, unless required by law forinteroperability, is prohibited.

    The information contained herein is subject to change without notice and is not warranted to be error-free. Ifyou find any errors, please report them to us in writing.

    If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it onbehalf of the U.S. Government, then the following notice is applicable:

    U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software,any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are"commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of theprograms, including any operating system, integrated software, any programs installed on the hardware,and/or documentation, shall be subject to license terms and license restrictions applicable to the programs.No other rights are granted to the U.S. Government.

    This software or hardware is developed for general use in a variety of information management applications.It is not developed or intended for use in any inherently dangerous applications, including applications thatmay create a risk of personal injury. If you use this software or hardware in dangerous applications, then youshall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure itssafe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of thissoftware or hardware in dangerous applications.

    Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks oftheir respective owners.

    Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks areused under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron,the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced MicroDevices. UNIX is a registered trademark of The Open Group.

    This software or hardware and documentation may provide access to or information about content, products,and services from third parties. Oracle Corporation and its affiliates are not responsible for and expresslydisclaim all warranties of any kind with respect to third-party content, products, and services unless otherwiseset forth in an applicable agreement between you and Oracle. Oracle Corporation and its affiliates will not beresponsible for any loss, costs, or damages incurred due to your access to or use of third-party content,products, or services, except as set forth in an applicable agreement between you and Oracle.

  • Contents

    PrefaceAudience vi

    Documentation Accessibility vi

    Related Resources vi

    Conventions vi

    1 Understanding the REST AdapterREST Adapter Capabilities 1-1

    About Oracle Integration Cloud Service 1-27

    About Oracle Integration Cloud Service Connections 1-28

    About Oracle Integration Cloud Service Integrations 1-28

    How to Implement Specific REST Adapter Features 1-28

    How Do I Build an Integration that Exposes the REST API Using the RESTAdapter? 1-29

    How Do I Configure the REST Adapter to Consume a REST API Protected with2-Legged OAuth Token-Based Authentication? 1-31

    How Do I Configure the REST Adapter to Consume a REST API Protected with3-Legged OAuth Token-Based Authentication? 1-36

    Security Configurations for Popular OAuth-Protected APIs 1-40

    Typical Workflow for Creating and Including an Adapter Connection in an Integration1-40

    2 Creating a REST Adapter ConnectionPrerequisites for Creating a Connection 2-1

    Uploading an SSL Certificate 2-2

    Creating a Connection 2-3

    Adding a Contact Email 2-4

    Configuring Connection Properties 2-4

    Configuring Connection Security 2-5

    Configuring an Agent Group 2-9

    Testing the Connection 2-9

    iii

  • Testing a REST Adapter Connection with the HTTP Basic AuthenticationSecurity Policy Does Not Validate the Credentials 2-9

    Editing a Connection 2-10

    Cloning a Connection 2-10

    Deleting a Connection 2-11

    3 Creating an Integration

    4 Adding the REST Adapter Connection to an IntegrationConfiguring REST Adapter Basic Information Properties 4-1

    What You Can Do from the REST Adapter Basic Info Page 4-2

    What You See on the REST Adapter Basic Info Page 4-2

    Configuring REST Adapter Request Parameters Properties 4-4

    What You Can Do from the REST Adapter Request Parameters Page 4-5

    What You See on the REST Adapter Request Parameters Page 4-5

    Configuring REST Adapter Request Properties 4-5

    What You Can Do from the REST Adapter Request Page 4-5

    What You See on the REST Adapter Request Page 4-6

    Configuring REST Adapter Request Header Properties 4-8

    What You Can Do from the REST Adapter Request Headers Page 4-8

    What You See on the REST Adapter Request Headers Page 4-9

    Configuring REST Adapter CORS Configuration Properties 4-9

    What You Can Do from the REST Adapter CORS Configuration Page 4-10

    What You See on the REST Adapter CORS Configuration Page 4-10

    Configuring REST Adapter Response Properties 4-10

    What You Can Do from the REST Adapter Response Page 4-10

    What You See on the REST Adapter Response Page 4-11

    Configuring REST Adapter Response Header Properties 4-13

    What You Can Do from the REST Adapter Response Headers Page 4-13

    What You See on the REST Adapter Response Headers Page 4-14

    Configuring Oracle REST Adapter Invoke Operation Selection Properties 4-14

    What You Can Do from the REST Adapter Operation Selection Page 4-15

    What You See on the REST Adapter Operation Selection Page 4-15

    Reviewing Configuration Values on the Summary Page 4-15

    What You Can Do from the Summary Page 4-15

    What You See on the Summary Page 4-16

    5 Creating Mappings and Lookups in IntegrationsEntering q as a Standard HTTP Query Parameter with the Query as a Value 5-1

    iv

  • JSON to XML Special Character Conversion 5-1

    6 Administering Integrations

    7 Troubleshooting the REST AdapterProcessing Large Sample JSON Files with Special Characters 7-1

    Using a Surrogate Namespace in Schemas Without a Namespace 7-2

    Troubleshooting SSL Certification Issues 7-3

    Defining Fault and Response Pipelines in Basic Map Data Integrations 7-3

    Empty Arrays Are Not Supported in Sample JSON Files 7-5

    Invoke Endpoint URI Must Match the Base URI + Resource URI in REST Adapter 7-5

    Invoking JD Edwards Form Service with the REST Adapter CausesAPIInvocationError 7-5

    REST Adapter Data is Only Saved When You Click Next 7-6

    Converting XML to a JSON Document 7-6

    Supported Special Characters in JSON 7-7

    content-type is Missing for an Asynchronous Flow 7-7

    REST URLs Exceeding 8251 Characters Fail 7-8

    v

  • Preface

    Using the REST Adapter describes how to configure the REST Adapter as aconnection in an integration in Oracle Integration Cloud Service.

    Topics

    • Audience

    • Documentation Accessibility

    • Related Resources

    • Conventions

    AudienceUsing the REST Adapter is intended for developers who want to use the RESTAdapter in integrations in Oracle Integration Cloud Service.

    Documentation AccessibilityFor information about Oracle's commitment to accessibility, visit the OracleAccessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc.

    Access to Oracle Support

    Oracle customers that have purchased support have access to electronic supportthrough My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trsif you are hearing impaired.

    Related ResourcesSee these Oracle resources:

    • Oracle Cloud

    http://cloud.oracle.com

    • Using Oracle Integration Cloud Service

    • Using the Oracle Mapper

    ConventionsThe following text conventions are used in this document:

    Preface

    vi

    http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacchttp://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacchttp://www.oracle.com/pls/topic/lookup?ctx=acc&id=infohttp://www.oracle.com/pls/topic/lookup?ctx=acc&id=infohttp://www.oracle.com/pls/topic/lookup?ctx=acc&id=trshttp://cloud.oracle.com

  • Convention Meaning

    boldface Boldface type indicates graphical user interface elements associatedwith an action, or terms defined in text or the glossary.

    italic Italic type indicates book titles, emphasis, or placeholder variables forwhich you supply particular values.

    monospace Monospace type indicates commands within a paragraph, URLs, codein examples, text that appears on the screen, or text that you enter.

    Preface

    vii

  • 1Understanding the REST Adapter

    Review the following conceptual topics to learn about the REST Adapter and how touse it as a connection in integrations in Oracle Integration Cloud Service. A typicalworkflow of adapter and integration tasks is also provided.

    Topics

    • REST Adapter Capabilities

    • About Oracle Integration Cloud Service

    • About Oracle Integration Cloud Service Connections

    • About Oracle Integration Cloud Service Integrations

    • Typical Workflow for Creating and Including an Adapter Connection in anIntegration

    REST Adapter CapabilitiesThe REST Adapter can expose integrations as REST APIs by configuring a RESTAdapter connection as a trigger. The REST Adapter can also consume any externalREST API by configuring a REST Adapter connection as an invoke. This sectionidentifies the capabilities of the REST Adapter when used as a trigger or invokeconnection.

    Note:

    The REST Adapter treats all endpoints as they are exposed. The RESTAdapter does not filter or change any of the APIs exposed by the applicationto which you are connecting. If there is a native adapter for the application towhich you are connecting, use that adapter instead. If you choose to use theREST Adapter instead of the native adapter, the API restrictions anddeprecation policies apply as specified in the respective application’sdocumentation.To connect to the Oracle HCM Cloud SOAP APIs, see Oracle HCM CloudAdapter Capabilities.

    The REST Adapter provides the following capabilities when exposing an integration asa REST API by configuring the connection as a trigger:

    • Support for uploading sample JSON documents to define schema during RESTAdapter configuration.

    • REST APIs implement the HTTPS protocol, thereby enforcing all incomingrequests to have transport level security.

    • REST APIs exposed using the REST Adapter are protected using BasicAuthentication and OAuth token-based authentication.

    1-1

  • • Supports configuration of the following:

    – Relative resource URI.

    – Support for HTTP methods GET, PUT, POST, DELETE, and PATCH.

    – Template and query parameters.

    – Support for a request/response payload.

    * Support for JSON, XML, and URL-form-encoded payloads.

    * Support for homogenous JSON arrays including top-level arrays.

    * Support for multidimensional JSON arrays (see HomogenousMultidimensional Array Support in JSON Documents).

    See Configuration Parameters.

    • Support for standard and custom HTTP headers to model an integration to exposestandard and custom HTTP header properties to Oracle Integration Cloud Servicefor downstream processing (see Standard and Custom Header Support).

    • Support for multipart attachments (content-types: multipart/mixed and multipart/form-data) in request/response messages while creating an integration to exposea REST endpoint that accepts incoming request messages with multipartattachments and/or sends responses with multipart attachments (see MultipartAttachment Support for Trigger and Invoke Connections).

    • REST APIs exposed using the REST Adapter can be configured to be CORS-compliant (see Cross-Origin Resource Sharing (CORS)).

    • Support for exposing a REST endpoint that can accept the request and process itasynchronously.

    • A Swagger 2.0–compliant document is automatically produced for REST APIsexposed using the REST Adapter. This document describes the metadata for thegenerated REST APIs (see Viewing the Metadata for the Inbound REST Endpointin Swagger Format).

    The REST Adapter provides the following capabilities when consuming external RESTAPIs by configuring the connection as an invoke:

    • Support for uploading sample XML documents to define schema for XML contentduring REST Adapter configuration. The following XML documents are supportedfor schema generation:

    – XML with no namespace

    – XML with a homogenous namespace

    – XML files up to 3 MB in size

    • Support for uploading sample JSON documents to define schema during RESTAdapter configuration.

    • Support for consuming any REST API described using Swagger 2.0/RAMLdocuments and the Oracle Metadata Catalog. The REST Adapter canautomatically discover and present the available resources and operations presentin the documents for configurations. The metadata regarding operation-specificrequest and response messages available in the document is automatically madeavailable for mapping and other activities. (see Swagger and RAML DocumentSupport for Describing External REST APIs).

    • Supports configuration of the following (see Configuration Parameters).

    Chapter 1REST Adapter Capabilities

    1-2

  • – Relative resource URI.

    – Support for HTTP methods GET, PUT, POST, DELETE, and PATCH.

    – Template and query parameters.

    – Support for a request/response payload:

    * Support for JSON, XML, and URL-form-encoded payloads.

    * Support for homogenous JSON arrays.

    * Support for multidimensional JSON arrays (see HomogenousMultidimensional Array Support in JSON Documents).

    * Delivery of form parameters as part of a request body.

    Note:

    The REST Adapter automatically encodes the value of query parametersbefore invoking a service. The REST Adapter has no way of knowing ifyou have already encoded a query parameter. Ensure that you assignunencoded values to query parameters. Assigning encoded values leadsto double encoding.

    For example, assume query parameter q has the following value:

    q=a+b

    This may mean that the value of q was intended to be a b, but wasencoded by the user.

    The intention may also have been to send a+b, which must be URL-encoded as a%2Bb before sending.

    • Support for accessing and setting standard and custom HTTP headers exposedby external REST APIs (see Standard and Custom Header Support).

    • Support for multipart attachments (content-type: multipart/mixed, multipart/form-data ) in request/response messages in an integration flow while sending arequest to an external REST endpoint that accepts incoming request messageswith multipart attachments and/or sends responses with multipart attachments(see Multipart Attachment Support for Trigger and Invoke Connections).

    • Support for consuming external REST APIs that are not described usingSwagger /RAML documents. You can declaratively specify the HTTP method andthe sample JSON document/XML schema for describing the shape of the requestand response messages.

    • Support for consuming external REST APIs that are protected using transport levelsecurity.

    • Support for consuming REST APIs protected using HTTP Basic Authentication,OAuth Client Credentials (two-legged flow), OAuth Resource Owner PasswordCredentials (two-legged flow), OAuth Authorization Code Credentials (three-legged flow), OAuth Custom Three Legged Flow, and OAuth Custom Two LeggedFlow. There is also support for consuming APIs that are unprotected.

    • Extensibility support to access plurality of OAuth 2 providers (see ExtensibilitySupport for Multiple OAuth Providers).

    Chapter 1REST Adapter Capabilities

    1-3

  • • Consumption of on-premises REST APIs residing behind the fire wall using theconnectivity agent (see On-Premises REST API Support with the Agent).

    • Support for dynamically changing the (invoke) outbound endpoint configuration(see Support for Dynamic REST Endpoints).

    Note:

    XML documents passed to a REST endpoint that support theapplication/XML content type must comply with the XML schema specifiedduring trigger (inbound) REST configuration. When the REST invokes atarget endpoint, the application/XML response must comply with the XMLschema specified during invoke (outbound) REST response configuration.

    The following sections describe these capabilities in more detail:

    • Configuration Parameters

    • Standard and Custom Header Support

    • Authentication Types

    • Extensibility Support for Multiple OAuth Providers

    • Role-Based Connections

    • Cross-Origin Resource Sharing (CORS)

    • Swagger and RAML Document Support for Describing External REST APIs

    • Homogenous Multidimensional Array Support in JSON Documents

    • Multipart Attachment Support for Trigger and Invoke Connections

    • On-Premises REST API Support with the Agent

    • Viewing the Metadata for the Inbound REST Endpoint in Swagger Format

    • RFC 3986 Support for Encoding Query Parameters

    • Support for application/octet-stream MIME Attachment (Raw) Payloads

    Configuration Parameters

    You configure the following parameters using the Endpoint Configuration Wizard toexpose and consume a REST service.

    • Relative resource path URI

    • HTTP method (actions) to perform

    • Template and query parameters

    • Request/response message structure

    Standard and Custom Header Support

    The REST Adapter supports standard and custom HTTP request and responseheaders in the invoke and trigger directions.

    • Outbound (Invoke) direction

    Chapter 1REST Adapter Capabilities

    1-4

  • HTTP headers enable you to use an outbound invocation to specify headerproperties. Many REST APIs expect certain properties to be specified in the HTTPheaders (similar to SOAP APIs where you can specify header properties such asthe WS address). Use the standard HTTP headers to specify these properties.You can also use the custom HTTP headers to specify properties. The REST APIscan expect the client application to pass properties in the custom headers, whichcan influence the behavior of the APIs. The standard and custom HTTP headerproperties configured in the wizard automatically start appearing in the mapperand the Expression Builder. You can map the header properties in the mapper.

    • Inbound (trigger) direction

    You can expose integration flows as REST endpoints and enable clientapplications to populate the properties in the standard and custom headers. Youcan use these properties to create routing expressions in your integrations. Thestandard and custom HTTP header properties configured in the wizardautomatically start appearing in the mapper and the Expression Builder. You canmap the header properties in the mapper. See Creating Routing Paths for TwoDifferent Invoke Endpoints in Integrations and Creating an OrchestratedIntegration.

    Note:

    • If you want to send multiple values of a header, use comma separatedvalues (CSVs). This is considered as one header and one value thatconsists of:

    val1 comma val2 comma val3 ...

    The same value is propagated across the mapper and then to theoutbound service. The outbound service must then interpret the CSVs ofthe header to be used as multiple values.

    • You cannot store multiple headers with the same name. The WSDL canonly store one element with one unique name.

    Authentication Types

    The REST Adapter supports the invocation of external REST endpoints supporting thefollowing types of authentication:

    • Basic Authentication

    • OAuth Client Credentials (two-legged flow)

    • OAuth Resource Owner Password Credentials (two-legged flow)

    • OAuth Authorization Code Credentials (three-legged flow)

    • OAuth Custom Three Legged Flow

    • OAuth Custom Two Legged Flow

    • OAuth 1.0a One Legged Authentication

    See Configuring Connection Security for more information about these securitypolicies.

    Chapter 1REST Adapter Capabilities

    1-5

  • Extensibility Support for Multiple OAuth Providers

    You can use the extensibility framework of the REST Adapter to access the OAuth-protected resource of endpoints. This framework enables you to access endpoints thathave implemented their own variations of OAuth.

    The OAuth standard provides flexibility for endpoints to define specific aspects of theirOAuth flows. For example:

    • Create their own properties.

    • Decide when to use these properties in an OAuth flow. For example, some customproperties may be required with the authorization request, while others may berequired for the access token request or for the refresh of the access token afterits expiration.

    • Decide how to pass these properties in an OAuth flow. For example, whether aproperty is passed as a header, query parameter, or payload.

    To address these challenges, Oracle Integration Cloud Service provides two customsecurity policies that enable you to specify each step in the OAuth flow when youcreate the REST Adapter connection:

    • OAuth custom two-legged flow: The client application directly interacts with theauthorization server on behalf of a resource owner.

    • OAuth custom three-legged flow: The client application redirects the owner to aseparate resource URL where the resource owner authenticates and providesconsent for the flow to continue.

    This enables you to adapt to most OAuth framework scenarios and integrate withmany third-party applications without writing additional code.

    • During design-time, the access token is obtained, validated, and stored in theCSF. The security token is also stored in the CSF.

    • During runtime, the access token is retrieved, applied, and managed. A validaccess token is applied to the request before invoking the REST endpoint.

    For information about specifying the OAuth custom two-legged flow and three-leggedflow security policies, see Configuring Connection Security and How to ImplementSpecific REST Adapter Features.

    Note:

    This extensibility feature is an advanced feature, and not for business users.Users of this feature should use a tool such as postman to configure thenecessary properties.

    Role-Based Connections

    The REST Adapter is bidirectional. You can configure the REST Adapter dependingon the context in which you want to use the connection.

    • Trigger: The REST Adapter is used to create a REST endpoint to trigger anintegration. You select Trigger from the Role list on the Create New Connectiondialog. When configured as a trigger, a base URI is not required. The securitypolicy defined in the inbound direction accepts credentials configured in the

    Chapter 1REST Adapter Capabilities

    1-6

  • identity domain. Therefore, you are not required to provide the applicablecredentials. When configuring security on the Connections page, you only providethe security policy that must be attached to the inbound endpoint. Basicauthentication is the only security policy available. Agent configuration is notapplicable on a connection with the trigger role.

    • Invoke: The REST Adapter is used to invoke external REST endpoints. A baseURI and security configuration for accessing external protected resources arerequired. You are prompted for these additional details on the Connections page.You cannot use an invoke connection on the trigger side.

    • Trigger and invoke: The REST Adapter is used in both the trigger and invokedirections of an integration. This connection requires invoke and trigger values.

    Cross-Origin Resource Sharing (CORS)

    CORS defines a way in which a browser and server can interact to determine safelywhether or not to allow the cross-origin request. CORS provides for more flexibilitythan same-origin requests, but is more secure than simply permitting all cross-originrequests.

    Oracle Integration Cloud Service supports CORS in the inbound direction.

    CORS is supported by browsers based on the following layout engines:

    • Blink- and Chromium-based browsers (Chrome 28, Opera 15, Amazon Silk,Android's 4.4+ WebView, and Qt's WebEngine).

    • Gecko 1.9.1 (Firefox 3.5, SeaMonkey 2.0, and Camino 2.1) and above.

    • MSHTML/Trident 6.0 (Internet Explorer 10) has native support. MSHTML/Trident4.0 & 5.0 (Internet Explorer 8 & 9) provide partial support through theXDomainRequest object.

    • Presto-based browsers (Opera) implement CORS as of Opera 12.00 and OperaMobile 12, but not Opera Mini.

    • WebKit (Safari 4 and above, Google Chrome 3 and above, possibly earlier).

    The following browsers do not support CORS:

    • Camino does not implement CORS in the 2.0.x release series because theseversions are based on Gecko 1.9.0

    • As of version 0.10.2, Arora exposes WebKit's CORS-related APIs, but attemptedcross-origin requests fail.[16]

    For CORS to work, you must send an OPTIONS request. Using the XMLHttpRequestobject in Javascript for (Ajax calls) automatically sends the OPTIONS request. IfXMLHttpRequest is not used, then the OPTIONS request must be sent explicitly.

    In the following example, an HTML client invokes an Oracle Integration Cloud ServiceCORS-based endpoint using XMLHttpRequest.

    var invocation = new XMLHttpRequest(); var url ="";// Use postman to generate authCode. Sample is provided below var authCode = 'Basic ';

    Chapter 1REST Adapter Capabilities

    1-7

  • function callOtherDomain(){ if(invocation) { invocation.open('GET', url, true); invocation.setRequestHeader('Accept', 'application/json'); invocation.setRequestHeader('X-Cache','aaa'); invocation.setRequestHeader('X-Forwarded-For','fwd1'); invocation.setRequestHeader('Authorization',authCode); invocation.onreadystatechange = stateChangeEventHandler; invocation.send(); } }

    function stateChangeEventHandler() { // check whether the data is loaded if (invocation.readyState==4) { // check whether the status is ok if (invocation.status==200) { //alert(invocation.responseText) document.getElementById("myTextarea").value = invocation.responseText document.write("hello"); document.write(invocation.responseText); } else { alert ("Error Occurred") } } }





    Some browsers may also have security restrictions such as the same origin policy or asimilar name that prevents using CORS. For example, to access a CORS-enabledendpoint using a Chrome browser, you may have to start it with web security disabledas follows.

    chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

    Swagger and RAML Document Support for Describing External REST APIs

    The REST Adapter provides support for consuming REST APIs that are described ineither a Swagger or RAML document

    • RESTful API Modeling Language (RAML): A language for describing RESTfulAPIs. RAML provides the information necessary to describe RESTful orpractically-RESTful APIs (APIs that do not obey all REST constraints).

    • Swagger: A specification for describing, producing, consuming, and visualizingRESTful web services.

    The following example shows a Swagger 2.0 file. This file contains two mainresources:

    • /Book. This resource contains get and post methods and /Book/{id}, /Book/hello,and /Book/search subresources.

    Chapter 1REST Adapter Capabilities

    1-8

  • • /Author. This resource contains a get method and an /Author/{id} subresource.

    When configuring an invoke (outbound) REST Adapter in the Endpoint ConfigurationWizard, the resources and subresources are displayed for selection as businessobjects and the methods are displayed for selection as operations to perform on thebusiness objects.

    When creating the REST Adapter connection, you select Swagger Definition URL inthe Connection Type field and specify the URL in the Connection URL field of theConnection Properties dialog.

    {

    "swagger" : "2.0", "info" : { "version" : "1.0", "title" : "RestServiceForBooks" },

    "host" : "host_name:8080", "basePath" : "/Test/rest", "schemes" : ["http"], "paths" : { "/Book" : { "get" : { "operationId" : "getBooks", "description" : "Returns all the available books in teh store", "produces" : [ "application/xml", "application/json" ], "responses" : { "default" : { "schema" : { "$ref" : "#/definitions/Books" } } }

    }, "post" : { "operationId" : "postBook", "description" : "Creates a new book item", "produces" : [ "application/xml", "application/json" ], "consumes" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "Book", "in" : "body", "required" : true, "schema" : { "$ref" : "#/definitions/Book" } } ], "responses" : { "default" : { "schema" : { "$ref" : "#/definitions/Book" } } } } }, "/Book/{id}" : { "get" : { "operationId" : "getSingleBook", "description" : "Returns a book with specific id",

    Chapter 1REST Adapter Capabilities

    1-9

  • "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name": "id", "in": "path", "required" : true, "type" : "string" } ], "responses" : { "default" : { "schema" : { "$ref" : "#/definitions/Book" } } } } }, "/Book/hello" : { "get" : { "operationId" : "sayHelloToBook", "description" : "says hello to a book", "produces" : [ "application/xml", "application/json" ], "responses" : { "default" : { "schema" : { "type" : "string" } } } } }, "/Book/search" : { "get" : { "operationId" : "searchBook", "description" : "Returns a list of books that match query param", "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name": "name", "in": "query", "required" : false, "type" : "string" } ], "responses" : { "default" : { "schema" : { "$ref" : "#/definitions/Books" } } } } }, "/Author" : { "get" : { "operationId" : "getAuthors", "description": "Returns a list of authors", "produces": [ "application/xml", "application/json" ], "responses": { "default": { "schema": {

    Chapter 1REST Adapter Capabilities

    1-10

  • "$ref" : "#/definitions/Authors" } } } } }, "/Author/{id}" : { "get" : { "operationId" : "getSingleAuthor", "description" : "Returns a Author with specific id", "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name": "id", "in": "path", "required" : true, "type" : "string" } ], "responses" : { "default" : { "schema" : { "$ref" : "#/definitions/Author" } } } } } }, "definitions" : { "Author" : { "type" : "object", "properties" : { "id" : { "type" : "string" }, "firstName" : { "type" : "string"}, "lastName" : { "type" : "string" } }, "required" : [ "id", "firstName", "lastName"] }, "Authors" : { "type" : "object", "properties" : { "items" : { "type" : "array", "items" : { "$ref" : "#/definitions/Author" } } } }, "Publisher" : { "type" : "object", "properties" : { "id" : { "type" : "string" }, "name" : { "type" : "string"}, "location" : { "type" : "string" } }, "required" : [ "id", "name", "location"] }, "Publishers" : { "type" : "object", "properties" : { "items" : {

    Chapter 1REST Adapter Capabilities

    1-11

  • "type" : "array", "items" : { "$ref" : "#/definitions/Publisher" } } } }, "Book" : { "type" : "object", "properties" : { "id" : { "type" : "string" }, "name" : { "type" : "string" }, "ISBN" : { "type" : "string" }, "price" : { "type" : "integer" }, "author" : { "type" : "array", "items" :{ "$ref" : "#/definitions/Author" } }, "publisher" : { "$ref" : "#/definitions/Publisher" } }, "required" : ["id", "name", "ISBN", "price", "author", "publisher" ] }, "Books" : { "type" : "object", "properties" : { "items" : { "type" : "array", "items" : { "$ref" : "#/definitions/Book" } } } } }}

    The following example shows a RAML file. The file contains the schemas that use theservice. This file contains two main resources:

    • /Author. This resource contains a get method and an /Author/{id} subresource.

    • /Book. This resource contains get and post methods and /Book/{id} and /Book/search subresources.

    When configuring an invoke (outbound) REST Adapter in the Endpoint ConfigurationWizard, the resources and subresources are displayed for selection as businessobjects and the methods are displayed for selection as operations to perform on thebusiness objects.

    When creating your REST Adapter connection, you select RAML Definition URL inthe Connection Type field and specify the URL in the Connection URL field of theConnection Properties dialog.

    #%RAML 0.8title: API for Booksversion: v1baseUri: "http://host_name:8080/Test/rest"protocols: [ HTTP ]schemas: - authors-jsonschema: | { "$schema" : "http://json-schema.org/draft-03/schema", "type":"object",

    Chapter 1REST Adapter Capabilities

    1-12

  • "properties":{ "items":{ "type":"array", "items":{ "type":"object", "properties":{ "id":{ "type":"string" }, "firstName":{ "type":"string" }, "lastName":{ "type":"string" } }, "required":[ "id", "firstName", "lastName" ] } } } } - author-jsonschema: | { "$schema":"http://json-schema.org/draft-03/schema",

    "type":"object", "properties":{ "id":{ "type":"string" }, "firstName":{ "type":"string" }, "lastName":{ "type":"string" } }, "required":[ "id", "firstName", "lastName" ] }

    - books-jsonschema: | { "$schema":"http://json-schema.org/draft-03/schema",

    "type":"object", "properties":{ "items":{ "type":"array", "items":{ "type":"object", "properties":{ "id":{ "type":"string"

    Chapter 1REST Adapter Capabilities

    1-13

  • }, "name":{ "type":"string" }, "ISBN":{ "type":"string" }, "price":{ "type":"integer" }, "author":{ "type":"array", "items":{ "type":"object", "properties":{ "id":{ "type":"string" }, "firstName":{ "type":"string" }, "lastName":{ "type":"string" } }, "required":[ "id", "firstName", "lastName" ] } }, "publisher":{ "type":"object", "properties":{ "id":{ "type":"string" }, "name":{ "type":"string" }, "location":{ "type":"string" } }, "required":[ "id", "name", "location" ] } }, "required":[ "id", "name", "ISBN", "price", "author", "publisher" ] }

    Chapter 1REST Adapter Capabilities

    1-14

  • } }

    } - book-jsonschema: | { "$schema":"http://json-schema.org/draft-03/schema", "type":"object", "properties":{ "id":{ "type":"string" }, "name":{ "type":"string" }, "ISBN":{ "type":"string" }, "price":{ "type":"integer" }, "author":{ "type":"array", "items":{ "type":"object", "properties":{ "id":{ "type":"string" }, "firstName":{ "type":"string" }, "lastName":{ "type":"string" } }, "required":[ "id", "firstName", "lastName" ] } }, "publisher":{ "type":"object", "properties":{ "id":{ "type":"string" }, "name":{ "type":"string" }, "location":{ "type":"string" } }, "required":[ "id", "name", "location" ]

    Chapter 1REST Adapter Capabilities

    1-15

  • } }, "required":[ "id", "name", "ISBN", "price", "author", "publisher" ] }/Author: get: responses: 200: body: application/xml: schema: authors-jsonschema example: | application/json: schema: authors-jsonschema example: | { "authors" : "" } /{id}: get: responses: 200: body: application/xml: schema: author-jsonschema example: | application/json: schema: author-jsonschema example: | { "author" : "" }/Book: post: body: application/xml: schema: book-jsonschema application/json: schema: book-jsonschema responses: 200: body: application/xml: schema: book-jsonschema example: | application/json:

    Chapter 1REST Adapter Capabilities

    1-16

  • schema: book-jsonschema example: | { "book" : { "price" : "" } } get: responses: 200: body: application/xml: schema: books-jsonschema example: | application/json: schema: books-jsonschema example: | { "book" : { "price" : "" } } /search: get: queryParameters: name: responses: 200: body: application/xml: schema: books-jsonschema example: | application/json: schema: books-jsonschema example: | { "book" : { "price" : "" } } /{id}: get: responses: 200: body: application/xml: schema: book-jsonschema example: | application/json:

    Chapter 1REST Adapter Capabilities

    1-17

  • schema: book-jsonschema example: | { "book" : { "price" : "" } }

    Homogenous Multidimensional Array Support in JSON Documents

    You can select a JSON sample with homogenous multidimensional arrays whenconfiguring the REST Adapter in the Configuration Wizard.

    All JSON messages must be converted to XML before they can be processed byOracle Integration Cloud Service at runtime. Semantically, there is no equivalent ofmultidimensional arrays in XML. To support multidimensional arrays, intermediateXML elements are generated that denote the beginning and ending of a nested array.When receiving a JSON message containing multidimensional arrays, these reservedelements are injected into the generated XML to denote the beginning and ending of anested array. While converting XML elements back into JSON, the injected elementsare converted into JSON with nested arrays.

    The following JSON document consists of a multidimensional array (@ref"rercordsData”).

    { "studentData": { "fieldNames": [ "id","mobile_number" ], "recordsData": [ ["21","23"], ["+91123456789", "+91987654321" ] ], "name": "jack" }, "schoolData": { "Name": "ABCInternations", "StudentNumbers": 1300, "Address": "YYY streets Sector-44 India" }}

    The sample generated schema XML for the JSON document looks as follows:

    id mobile_number 21 23 +91123456789 +91987654321

    Chapter 1REST Adapter Capabilities

    1-18

  • jack ABCInternations 1300 YYY streets Sector-44 India

    Elements in the nested array appear as nestedArray in the mapper and items in theelements appear as nestedArrayItem. You must map nestedArray as a for-eachstatement and nestedArrayItem as a for-each statement.

    Multipart Attachment Support for Trigger and Invoke Connections

    The REST Adapter supports multipart attachments for trigger (inbound) and invoke(outbound) requests.

    For example, you can send a review document attachment with the trigger (inbound)REST Adapter to an invoke (outbound) Adobe eSign or DocuSign for delivery to thedownstream endpoint for signing.

    If you want to send attachments from inbound to outbound (in request messages) or todownload attachments from outbound to inbound (in response messages), then foreach attachment you must map the attachmentReference from source to target in themapper.

    If you do not map attachmentReference in the mapper for a request, the outboundREST Adapter does not receive attachments from the inbound direction (multipartrequest). Similarly, if you do not map attachmentReference in the mapper for aresponse, the inbound REST Adapter does not receive attachments from the outboundREST Adapter (multipart response).

    Chapter 1REST Adapter Capabilities

    1-19

  • It is important to understand the data structures of different types of configurationsmade using the REST Adapter or any application adapter exposing the REST API(used as a trigger) or consuming the REST API (used as an invoke).

    There are two configuration categories of multipart request and response:

    • A — Multipart/mixed or multipart/form-data configured with JSON or XML samples

    This configuration uses the attachments schema and payload schema. Thepayload schema is derived based on a sample JSON/XML schema providedduring configuration in the Adapter Endpoint Configuration wizard.

    • B — Multipart/form-data with HTML form payload

    Note:

    This category is used when you select Request is HTML Form in theRequest page of the Adapter Endpoint Configuration wizard. This issimilar for a response if you select Response is HTML Form in theResponse page of the Adapter Endpoint Configuration wizard.

    This configuration uses the attachments schema and a generic schema with aParameterList element. The ParameterList element consists of an unboundedparameter element. Each parameter has a name attribute. The value of theparameter is set directly to the parameter element. If there are multipleparameters, the parameter element can be repeated in the mapper. The datatypeof the parameter and name is string.

    Note the following details about both configuration categories:

    • Attachments schema

    The attachments element has an unbounded attachment element. Thisconfiguration supports receiving (on the source) or sending (on the target) multipleattachments. Each attachment element has attachmentReference andattachmentProperties.

    • The AttachmentReference element contains the location where the attachmenthas been staged for access.

    The AttachmentProperties element provides metadata about a singleattachment:

    – The contentId property sets the Content-ID header of the body part. TheContent-ID header sets a unique ID for the body part.

    – The contentType property sets the Content-Type header of the body part.For example, if a PDF file is sent, the contentType property should beapplication/pdf. If the source is providing a multipart attachment, this isdetermined automatically. The mapper can set/override these values.

    – The transferEncoding property sets the Content-Transfer-Encoding headerof the body part. This header's value is a single token specifying the type ofencoding:

    Content-Transfer-Encoding := "BASE64" / "QUOTED-PRINTABLE" / "8BIT" / "7BIT" / "BINARY" / x-token

    Chapter 1REST Adapter Capabilities

    1-20

  • These values are not case sensitive. That is, Base64, BASE64, and bAsE64are all equivalent. An encoding type of 7BIT requires that the body is alreadyin a seven-bit, mail-ready representation. This is the default value (that is,Content-Transfer-Encoding: 7BIT is assumed if the Content-Transfer-Encoding header field is not present). See https://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html.

    – The partName property sets the fileName of the body part. The attached file/body part is saved by the target system with this name.

    – The contentDisposition property sets the Content-Disposition header of thebody part.

    In a multipart/form-data body, the HTTP Content-Disposition is a header touse on the subpart (that is, the attachment) of a multipart body to provideinformation about the field to which it applies. The Content-Dispositionheader value is generally set to form-data. The optional directive name andfilename can also be used. For example:

    Content-Disposition: form-dataContent-Disposition: form-data; name="fieldName"Content-Disposition: form-data; name="fieldName"; filename="filename.jpg"

    – The contentDescription property sets some descriptive information with agiven body part. For example, you can mark an image body as a picture ofthe Space Shuttle Endeavor. You can place such text in the Content-Description header field.

    – The fileInputHtmlFieldName property sets the name of the part from whichthe server must read the file.

    Mapper configuration scenarios:

    • Both source and target have multipart requests with JSON/XML payload (categoryA)

    The following sample map focuses only on the mapping of attachmentReferenceto the target. In this scenario, there is an assumption that only one attachmentfrom the source is being mapped to the target. The mapping of the payload(request-wrapper node) between the source and target is not shown. You mustperform that task.

    • Source is multipart/mixed or multipart/form-data with JSON/XML payload(Category A). Target is multipart/form-data with form fields (Category B)

    The following map focuses on mapping of the attributes on the HTML form. Theremust be as many parameters in the parameterList as there are fields in the HTMLform.

    Chapter 1REST Adapter Capabilities

    1-21

    https://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.htmlhttps://www.w3.org/Protocols/rfc1341/5_Content-Transfer-Encoding.html

  • • Creating reference from base64–encoded content. The source has a base64–encoded string and the target can be any of the three: multipart/mixed, multipart/form-data with JSON/XML payload, or multipart/form-data with HTML formpayload.

    In the inbound payload, the content element is a base64–encoded string. Thiscan be sent as an attachment in the outbound request.

    Since the inbound request is not multipart, but the outbound must be multipart, youmust set multipart-specific properties in the mapper for the outbound direction. ThecontentType is set here to image/png, partName is set to picture.png, andfileInputHtmlFieldName is set to image. The assumption is that the targetsystem is configured to read from a body part having name="image" in its contentdisposition. This is done with the element fileInputHtmlFieldName.

    The base64 string can be converted into a reference using XSL functiondecodeBase64ToReference and the reference can be assigned to theattachmentReference element.

    Chapter 1REST Adapter Capabilities

    1-22

  • • The inbound is an FTP file read operation (nonmultipart) and the outbound ismultipart/mixed with a JSON or XML payload.

    Note:

    • If the source is not multipart, but the target must be multipart,contentType and partName must be provided for the target through themapper.

    • The response mapper description is similar to the request mapper.

    On-Premises REST API Support with the Agent

    Oracle Integration Cloud Service provides an agent framework that enables you tocreate integrations and exchange messages between on-premises applications andOracle Integration Cloud Service. You can integrate on-premises REST APIs withOracle Integration Cloud Service through use of the on-premises agent. Once youcreate an agent group and install the on-premises agent, you can create and configurea REST Adapter connection as follows:

    • Select REST API Base URL or Swagger Definition URL from the ConnectionType list and enter the appropriate URL in the Connection URL field of theConnection Properties dialog. No other connection types are supported.

    • Select Basic Authentication or No Security Policy from the Security Policy listof the Credentials dialog. No other security policies are supported.

    Chapter 1REST Adapter Capabilities

    1-23

  • • Select the previously-created agent group in the Select an Agent Group dialog.

    For conceptual information about the on-premises agent, see About Agents andIntegrations Between On-Premises Applications and Oracle Integration Cloud Service.For information about creating an agent group and installing the on-premises agent,see Managing Agent Groups and the On-Premises Agent.

    Viewing the Metadata for the Inbound REST Endpoint in Swagger Format

    You can view the metadata of an activated REST integration and then append /swagger to the metadata URL to view the Swagger format for the integration. Theinbound REST integration can then be exposed as a Swagger connection.

    1. On the Integrations page, find the integration whose endpoint URL you want touse.

    2. Click the Details icon at the far right.

    3. Click the Endpoint URL value (for example, http://myPODname:7002/integration/flowapi/rest/GET_ONE_BOOK/v01/metadata).

    4. Append /swagger to the end of the URL, and press Enter.

    Appending /swagger to the URL generates a Swagger document for the inboundintegration. This URL can also be used to create a new Swagger connection in theConnection Properties dialog. You enter the Swagger URL in the ConnectionURL field and select Swagger Definition URL from the Connection Type field.

    RFC 3986 Support for Encoding Query Parameters

    The REST supports encoding query parameters in accordance with RFC 3986standards. The default behavior is to encode the query parameters following theapplication/x-www-form-urlencoded scheme. For most older services that expect queryparameters to be encoded following the application/x-www-form-urlencoded scheme,the default scheme should work. If you find the target endpoint not behaving correctlywith the default encoding scheme, the REST can also be configured to strictly followRFC 3986. A very common scenario in which the default behavior may not bedesirable is when the target service expects space characters encoded as %20 in thequery parameters. In this case, the default behavior is to encode space characters as+. Some new services may also respond with HTTP 400 (bad data) if query parametersare encoded in the application/x-www-form-urlencoded scheme. In these cases, youcan switch to the RFC 3986 standard and check if the service responds correctly. Touse RFC 3986 (and override the default behavior), perform the following steps to

    Chapter 1REST Adapter Capabilities

    1-24

    https://tools.ietf.org/html/rfc3986

  • configure the REST as an invoke connection (and not as a trigger connection) in theEndpoint Configuration Wizard and in the mapper.

    1. On the Basic Info page, select the Custom check box for Configure RequestHeaders.

    2. On the Request Headers page, add the x-ics-use-x-www-form-urlencoded customheader and optionally provide a description.

    3. Complete the wizard.

    4. In the mapper, set the x-ics-use-x-www-form-urlencoded custom header tofalse.

    The REST automatically encodes all query parameters in accordance with RFC 3986in the outgoing request for this invoke connection.

    Support for application/octet-stream MIME Attachment (Raw) Payloads

    A MIME attachment with the content type application/octet-stream is a binary file.Typically, it is an application or a document that is opened in an application such as aspreadsheet or word processor. If the attachment has a filename extension associatedwith it, you may be able to determine what type of file it is. For example, a .exeextension indicates a Windows or DOS program (executable), while a file endingin .doc is probably meant to be opened in Microsoft Word.

    The application/octet-stream MIME type is used for unknown binary files. Itpreserves the file contents, but requires the receiver to determine file type, forexample, from the filename extension. The Internet media type for an arbitrary bytestream is application/octet-stream.

    To use this feature, select the Raw option from the invoke Request/Response pagewhen configuring the adapter as an invoke. When you select this option, you need notprovide a schema because the payload has no structure.

    This feature works with the application/octet-stream MIME type and any other typethat can be sent as raw bytes. For example, the REST Adapter can send outboundrequests or process outbound responses using the application/pdf, application/zip,image/jpeg, image/png, and other formats. Commonly used types shown in thedropdown are:

    • application/octet-stream

    • application/pdf

    • application/msword

    • application/zip

    • image/jpeg

    • image/png

    • image/bmp

    • image/gif

    There is also a text box you can use to provide a type not listed in the dropdown list—for example, video/mp4 or text/csv.

    The following screenshots show how raw payloads can be mapped.

    Chapter 1REST Adapter Capabilities

    1-25

  • Complex Schema Support

    Support is provided for XSDs that can import and include other XSDs. The includedXSDs in the ZIP file can import the XSD from an HTTP location. All XSD files must beadded to a ZIP file and uploaded when configuring the REST Adapter in the AdapterEndpoint Configuration Wizard.

    In the following example, the hierarchy of the ZIP file to upload is as follows:

    zipxsd.zip first.xsd second (folder) second.xsd

    first.xsd imports second.xsd.

    Chapter 1REST Adapter Capabilities

    1-26

  • The contents of second.xsd are as follows.

    Note:

    If you are importing from HTTPS locations, ensure that you import the SSLcertificates into Oracle Integration Cloud Service.

    About Oracle Integration Cloud ServiceOracle Integration Cloud Service is a complete, secure, but lightweight integrationsolution that enables you to connect your applications in the cloud. It simplifiesconnectivity between your applications and connects both your applications that live inthe cloud and your applications that still live on premises. Oracle Integration CloudService provides secure, enterprise-grade connectivity regardless of the applicationsyou are connecting or where they reside.

    Oracle Integration Cloud Service provides native connectivity to Oracle Software as aService (SaaS) applications, such as Oracle Sales Cloud, Oracle RightNow Cloud,and so on. Oracle Integration Cloud Service adapters simplify connectivity by handlingthe underlying complexities of connecting to applications using industry-wide bestpractices. You only need to create a connection that provides minimal connectivityinformation for each system. Oracle Integration Cloud Service lookups map thedifferent codes or terms used by the applications you are integrating to describe

    Chapter 1About Oracle Integration Cloud Service

    1-27

  • similar items (such as country or gender codes). Finally, the visual data mapperenables you to quickly create direct mappings between the trigger and invoke datastructures. From the mapper, you can also access lookup tables and use standardXPath functions to map data between your applications.

    Once you integrate your applications and activate the integrations to the runtimeenvironment, the dashboard displays information about the running integrations so youcan monitor the status and processing statistics for each integration. The dashboardmeasures and tracks the performance of your transactions by capturing and reportingkey information, such as throughput, the number of messages processed successfully,and the number of messages that failed processing. You can also manage businessidentifiers that track fields in messages and manage errors by integrations,connections, or specific integration instances.

    About Oracle Integration Cloud Service ConnectionsConnections define information about the instances of each configuration you areintegrating. Oracle Integration Cloud Service includes a set of predefined adapters,which are the types of applications on which you can base your connections, such asOracle Sales Cloud, Oracle Eloqua Cloud, Oracle RightNow Cloud, and others. Aconnection is based on an adapter. For example, to create a connection to a specificRightNow Cloud application instance, you must select the Oracle RightNow adapterand then specify the WSDL URL, security policy, and security credentials to connect toit.

    Video

    About Oracle Integration Cloud Service IntegrationsIntegrations are the main ingredient of Oracle Integration Cloud Service. An integrationincludes at the least a trigger (source) connection (for requests sent to OracleIntegration Cloud Service) and invoke (target) connection (for requests sent fromOracle Integration Cloud Service to the target) and the field mapping between thosetwo connections.

    When you create your integrations, you build on the connections you already createdby defining how to process the data for the trigger (source) and invoke (target)connections. This can include defining the type of operations to perform on the data,the business objects and fields against which to perform those operations, requiredschemas, and so on. To make this easier, the most complex configuration tasks arehandled by Oracle Integration Cloud Service. Once your trigger (source) and invoke(target) connections are configured, the mappers between the two are enabled so youcan define how the information is transferred between the trigger (source) and invoke(target) data structures for both the request and response messages.

    Video

    How to Implement Specific REST Adapter FeaturesThe REST Adapter can be used to implement the following categories of use cases.

    • How Do I Build an Integration that Exposes the REST API Using the RESTAdapter?

    Chapter 1About Oracle Integration Cloud Service Connections

    1-28

    http://apexapps.oracle.com/pls/apex/f?p=44785:265:0::::P265_CONTENT_ID:11240http://apexapps.oracle.com/pls/apex/f?p=44785:265:0::::P265_CONTENT_ID:11241

  • • How Do I Configure the REST Adapter to Consume a REST API Protected with 2-Legged OAuth Token-Based Authentication?

    • How Do I Configure the REST Adapter to Consume a REST API Protected with 3-Legged OAuth Token-Based Authentication?

    • Security Configurations for Popular OAuth-Protected APIs

    Note:

    When you provision a new instance of Oracle Integration Cloud Service,several sample integrations are automatically included. Many of thesesamples are configured with the REST Adapter. These fully designedsamples help you get up and running quickly and show you how easy it is toactivate, invoke, and monitor an integration between endpoints.

    How Do I Build an Integration that Exposes the REST API Using theREST Adapter?

    The REST Adapter can be used in scenarios such as integrating with Twitter. Twitterprovides several REST endpoints for accessing resources. This use case describeshow to access a protected resource from Twitter using the Basic Authenticationsecurity policy.

    Obtain the Twitter Credentials

    1. Obtain the necessary Twitter connection details from the Twitter developer page at https://dev.twitter.com. These keys are required for configuring the Twitter Adapteron the Connections page. See Using the Twitter Adapter for specific details.

    • Consumer key

    • Consumer secret

    • Access token

    • Access token secret

    Configure the Twitter Adapter

    1. In the Credentials dialog on the Connections page of Oracle Integration CloudService, complete the following fields with the information obtained from Twitter.Note that the Custom Security Policy security policy is displayed by default, andcannot be deselected.

    • In the Consumer Key field, enter the consumer key.

    • In the Consumer Secret field, enter the consumer secret.

    • In the Access Token field, enter the access token.

    • In the Access Secret field, enter the access token secret.

    Configure the REST Adapter

    1. In the Connections page of Oracle Integration Cloud Service, complete thefollowing fields.

    Chapter 1How to Implement Specific REST Adapter Features

    1-29

    https://dev.twitter.comhttps://www.oracle.com/pls/topic/lookup?ctx=oic&id=ICSTW-GUID-A7CE3D09-3C89-4DEC-A07F-FA209960B355

  • • In the Connection Properties dialog, select REST API Base URL and specifythe connection URL.

    • In the Credentials dialog, select Basic Authentication as the security policyand specify the applicable user name and password.

    Create an Integration

    1. Drag a REST Adapter to the trigger side, and configure it as follows:

    • Specify the following parameters on the Basic Info page:

    – Select the POST action.

    – Select Configure a request payload for this endpoint.

    – Select Configure this endpoint to receive the response.

    • Specify the request schema on the Request page.

    • Specify the response schema on the Response page.

    2. Drag a Twitter Adapter to the invoke side, and configure it as follows:

    • Select the Tweet operation.

    3. In the request mapper, configure the appropriate source to target mapping.

    4. In the response mapper, configure the appropriate source to target mapping.

    When complete, the integration looks as follows.

    Invoke the Integration

    1. Invoke the integration from a browser:

    https://host:port/integration/flowapi/rest/TWEET/v01/tweet?status=Hi Twitter from ICS

    This posts the request status to Twitter.

    2. Log in to the Twitter account.

    3. Note the request message and the response message.

    Chapter 1How to Implement Specific REST Adapter Features

    1-30

  • How Do I Configure the REST Adapter to Consume a REST APIProtected with 2-Legged OAuth Token-Based Authentication?

    This section provides an overview of the OAuth Custom Two Legged Flow securitypolicy. This policy is useful when the Basic Authentication security policy is notsufficient.

    Most HTTP services typically use the OAuth authorization framework to protect theirresources. In accordance with the OAuth 2.0 specification, the OAuth 2.0 authorizationframework enables a third-party application to obtain limited access to an HTTPservice, either on behalf of a resource owner by orchestrating an approval interactionbetween the resource owner and the HTTP service or by enabling the third-partyapplication to obtain access on its own behalf.

    The REST Adapter enables you to integrate with any REST-enabled service includingOAuth services. To interact with an OAuth endpoint, you must create a one-timereusable connection on the Connections page of Oracle Integration Cloud Service.Configure the connection with the base URI and security configuration.

    The following security policy options are available in the Credentials dialog of theConnections page for the REST Adapter.

    Each option is applicable in a different context and is used to negotiate and obtain avalid access token. Read your REST service provider documentation to identify theapplicable policy.

    The following section describes a flexible OAuth security policy that can be used intwo-legged OAuth flows called as an OAuth Custom Two Legged Flow.

    OAuth 2.0 specification defines the following four OAuth flows:

    • OAuth Client Credentials

    • OAuth Resource Owner Password Credentials

    • OAuth Implicit Grant Authorization

    • OAuth Authorization Code Credentials

    The OAuth Client Credentials and OAuth Resource Owner Password Credentialsoptions are categorized as two-legged OAuth flows because the client applicationdirectly obtains access on its own without the resource owner’s intervention.

    An HTTP request is typically sent to the authorization server passing the clientapplication credentials (note that these are different from the resource ownercredentials and can be obtained by registering the client application with theauthorization server), the grant type and scope, and other required properties. The

    Chapter 1How to Implement Specific REST Adapter Features

    1-31

  • authorization server responds to this request by sending an access token, optionallywith a token type, an expiry, and sometimes a refresh token.

    The following example describes a sample access token request with Twitter (apopular microblogging site that supports OAuth2). For more information about Twitterdeveloper documentation, visit https://dev.twitter.com/oauth/application-only.

    POST /oauth2/token HTTP/1.1Host: api.twitter.comContent-Type: application/x-www-form-urlencodedAuthorization: Basic a3NmM1yRnFweAx==

    grant_type=client_credentials

    According to the Twitter developer documentation, this request is required to obtain anaccess token from Twitter. An HTTP basic authentication header is created by usingthe client ID and client secret.

    If the request is formatted correctly, the server responds with a JSON-encodedpayload. This is fairly straight forward.

    {"token_type":"bearer","access_token":"AAAAAAAAAA"}

    The following steps describe the OAuth Custom Two Legged Flow security policyand each field in the context of this scenario.

    Step 1: Configure the Access Token Request

    The Access Token Request field is formed using the URI syntax of the HTTP requestused to fetch the access token. The URI syntax resembles cURL but is more basic andonly supports the following options.

    Chapter 1How to Implement Specific REST Adapter Features

    1-32

    https://dev.twitter.com/oauth/application-only

  • Option Value Description Required

    -X GET | PUT | POST The HTTP verb in theaccess token request.

    Yes

    -H -H “key: value” Add each header keyvalue pair asdescribed. There canbe multiple headers.

    No

    -d -d ‘data-as-string’ String data enclosedwithin single quotes.Escape any quoteswithin the data string.

    No

    URI Uri (within quotes) - - Yes

    Note:

    • Other curl options are not supported.

    • The easiest way to build this request is to use a free tool such asPOSTMAN to build and validate the HTTP request to obtain an accesstoken and then use the Generate Code Snippet/Code option to get acURL syntax. Remove the curl from the beginning to get the URI syntax.The following example shows URI syntax:

    -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic a3NmM0J6czJG==" -d 'grant_type=client_credentials' https://api.twitter.com/oauth2/token

    The URI syntax allows you to control the access token request. The following is atypical access token response.

    { "access_token": "1-253912-240049694-f85c1d679211c", "expires_in": 21599, "token_type": "Bearer", "refresh_token": "5707efdf04912f53b61cb5ec5dc7f166"}

    Step 2: Parse and Extract Tokens from Access Token Response

    Note:

    Skip this step if the access token response has properties as highlightedpreviously.

    If the request is good, the authorization server returns an HTTP response with asuccess status. The response contains the access token and may also contain severaloperational details about the token such as the type of the token, its expiry, andrefresh token as described previously.

    Chapter 1How to Implement Specific REST Adapter Features

    1-33

  • By default, the $variables are mapped to property names containing relevant tokensas follows:

    Property Name Default Mapping to aProperty with Name

    Example Property Name

    $access_token access.[tT]oken access_token$refresh_token refresh.[tT]oken refresh_token$token_type token.?[tT]ype token_type$expiry expires_in expires_in

    The default values match the sample response. Therefore, this step is not requiredand can be skipped.

    However, if the access token response is not standard, then you must define rules tofetch tokens from the access token response.

    For example, assume the access token response is as follows:

    { "access_token": "1-253912-240049694-f85c1d679211c", "expiry": 21599, "token_type": "Bearer", "extended_token": "5707efdf04912f53b61cb5ec5dc7f166" }

    In this case, the authorization server returns a response, but chooses to specify theexpiry and the refresh token differently. This step is required to map these propertiesto the variables.

    Variable Name Default Mapping to aProperty with Name

    Example Property Name

    $refresh_token extended_token extended_token

    $expiry Expiry Expiry

    Chapter 1How to Implement Specific REST Adapter Features

    1-34

  • Variables can be used in the configuration using the ${variable} syntax once a valuehas been assigned. For example, $access_token is assigned a value after an accesstoken request is made. The value of this variable may be useful while specifying theaccess_token usage or the refresh_token_request later.

    Step 3: Access Token Usage (Important)

    Access token usage describes how to pass the access token to access a resource.Enter this information carefully because this usage governs how Oracle IntegrationCloud Service passes the negotiated access token to the endpoint.

    The default value for this field is:

    -H Authorization: ${token_type} ${access_token}

    At runtime, the values of ${token_type} and ${access_token} are retrieved based on thefetch rule and passed as an authorization header along with the endpoint request.

    The literal value can also be used as follows:

    -H API-Token: Bearer ${access_token}

    Access Token Usage Description Example

    -H Authorization: ${token_type} ${access_token}

    The access token is passedas a header at runtime foraccessing the protectedresource.

    -H Authorization: BearerAASDFADADX

    ?api_key=${access_token}The access token is passedas a query parameter atruntime for accessing theprotected resource.

    http://someapi.com/employee?api_key=ASDFADAX

    Chapter 1How to Implement Specific REST Adapter Features

    1-35

  • Step 4: Refresh Token Request (Optional)

    Some providers provide a mechanism to refresh a given access token. This sort ofmethod is generally part of an ROPC flow. However, there have been instances whereyou also use this with client credentials even when the specification says otherwise.

    The refresh token request typically takes the refresh token and returns a new accesstoken as a response along with operational attributes such as the type of token, itsexpiry, and another refresh token.

    The refresh token request must also be specified in a syntax similar to the accesstoken request and prescribes to the same rules.

    A sample refresh token request is as follows:

    -X POST 'https://sample.com/oauth2/token?refresh_token=${refresh_token}&client_id=[YOUR_CLEINT_ID]&client_secret=[YOUR_CLIENT_SECRET]&grant_type=refresh_token'

    This request contains a variable that is replaced with the actual value of the currentrefresh token at runtime.

    How Do I Configure the REST Adapter to Consume a REST APIProtected with 3-Legged OAuth Token-Based Authentication?

    This section provides an overview of the OAuth Custom Three Legged Flow securitypolicy.

    The following steps are performed as part of OAuth authorization code credentialsflow.

    Chapter 1How to Implement Specific REST Adapter Features

    1-36

  • Step

    Description

    1 The user specifies the authorization request URI. The user is redirected by the user agent(browser) to the authorization URI.

    2 The resource owner logs in to authenticate and provide consent to the client application toaccess its resources.

    3 The authorization server sends a callback request to the client application and sends theauthorization code.

    4 The client application extracts the authorization code from the request and uses it to sendanother request to the authorization server to get an access token.

    5 The authorization server responds to the access token request by sending an accesstoken to the client application.

    6 The client application uses the access token to make requests for protected resources.

    This flow is defined in the OAuth specification. However, how to perform each step inthe flow is determined by the authorization server implementing the OAuth flow. Thereare several variations to this flow.

    • The OAuth provider expects that some query parameters are passed when theuser is redirected to the authorization URI.

    • The provider calls the authorization code something else.

    Chapter 1How to Implement Specific REST Adapter Features

    1-37

  • • The call for the access token should include the authorization code. However,some providers may expect it as a header or a query parameter or maybe as partof the data.

    • The access token response may also wary. Some providers may return a refreshtoken (for example, call it extended_token or something else). Providers areknown to return an expiry, whereas some providers return a JWT token, where theexpiry is embedded as a claim within the token.

    • Providers may also declare a custom token type.

    • The call to refresh the access token may also vary from provider to provider.

    • The call to access resources using the access token may also vary. Providers mayexpect it to be a header or a query parameter. Some providers ask the token to bepassed as an authorization header. Few providers expect a custom header, andso on.

    The REST Adapter provides a security policy called the OAuth Authorization CodeCredentials Flow. This policy provides a specific implementation of the OAuth asillustrated in the OAuth specification. For all other cases, OAuth Custom ThreeLegged Flow can be used to address these customizations.

    Step 1: Configure the Authorization Request

    Specify the authorization URI where the resource owner authenticates and providesconsent in the Authorization Request field. The client ID and scope are typicallypassed as query parameters with the redirect URI from where the authorization servermust send a callback and the authentication code.

    Chapter 1How to Implement Specific REST Adapter Features

    1-38

  • Oracle Integration Cloud Service has a fixed endpoint to receive this callback so youcan specify the URI directly or pass a reference ${refresh_token} that is automaticallyresolved by the platform. For example:

    https://AUTH_URI?response_type=code&client_id=YOUR_CLIENT_ID &redirect_uri=${redirect_uri}&scope=app_scope

    Step 2: Configure the Access Token Request

    When the resource owner provides consent, the authorization server sends a callbackto the client application along with the authorization code. The next step is for theclient application to send a request for the access token using this authorization code.

    If the authorization server returns the authorization code in a property named asanything but code, you must map the property name with $auth_code.

    The access token request is used to make a call for the access token. It is supposedto send the authorization code that is not resolved until the flow is executed.Therefore, the authorization code is passed by reference as ${auth_code} in therequest.

    The rules for creating the access token request remain unchanged from the OAuthCustom Two legged Flow option.

    The Access Token Request value is formed using a URI syntax of the HTTP requestused to fetch the access token. The URI syntax resembles cURL, but it is more basicand only supports the following options.

    Option Value Description Required

    -X GET | PUT | POST The HTTP verb in theaccess token request.

    Yes

    -H -H “key: value” Add each header keyvalue pair asdescribed. There canbe multiple headers.

    No

    -d -d ‘data-as-string’ String data enclosedwithin single quotes.Escape any quoteswithin the data string.

    No

    URI Uri (within quotes) - - Yes

    Note:

    • Other curl options are not supported.

    • The easiest way to build this request is to use a free tool such asPOSTMAN to build and validate the HTTP request to obtain an accesstoken and then use the Generate Code Snippet/Code option to get acURL syntax. Remove the curl from the beginning to get the URI syntax.The following example shows the URI syntax:

    -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'false' 'https://access_token_URI?code=${auth_code}&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=${redirect_uri}&grant_type=authorization_code'

    Chapter 1How to Implement Specific REST Adapter Features

    1-39

    https://%3cauthURI%3e?response_type=code&client_id=[YOUR_CLIENT_ID]%20&redirect_uri=$%7bredirect_uri%7d&scope=%3capp_scope%3ehttps://%3cauthURI%3e?response_type=code&client_id=[YOUR_CLIENT_ID]%20&redirect_uri=$%7bredirect_uri%7d&scope=%3capp_scope%3e

  • Step 3: Optionally Configure the Refresh Token Request

    Similar to an access token request, specify the refresh token request in URI syntax, ifthe authorization server supports a refresh.

    Step 4: Define the Fetch Rules for Intermediate Tokens

    By default, the $variables are mapped to property names containing relevant tokensas follows:

    Property Name Default Mapping to aProperty with Name

    Example Property Name

    $auth_code code code$access_token access.[tT]oken access_token$refresh_token refresh.[tT]oken refresh_token$token_type token.?[tT]ype token_type$expiry expires_in expires_in

    This step is not required and can be skipped.

    However, if the access token response is not standard, then you must define rules tofetch tokens from the access token response.

    Step 5: Define the Access Token Usage (Important)

    Access token usage describes how to pass the access token to access a resource.Enter this information carefully because this usage governs how Oracle IntegrationCloud Service passes the negotiated access token to the endpoint.

    Security Configurations for Popular OAuth-Protected APIsYou can configure the REST Adapter connection to consume OAuth-protected popularAPIs.

    See this blog.

    Typical Workflow for Creating and Including an AdapterConnection in an Integration

    You follow a very simple workflow to create a connection with an adapter and includethe connection in an integration in Oracle Integration Cloud Service.

    Step Description More Information

    1 Create the adapter connectionsfor the applications you want tointegrate. The connections canbe reused in multipleintegrations and are typicallycreated by the administrator.

    Creating a REST Adapter Connection

    Chapter 1Typical Workflow for Creating and Including an Adapter Connection in an Integration

    1-40

    https://blogs.oracle.com/adapters/integrate-ics-with-a-third-party-oauth-protected-rest-service-using-the-generic-rest-adapter-part-3

  • Step Description More Information

    2 Create the integration. Whenyou do this, you add trigger andinvoke connections to theintegration.

    Creating an Integration and Adding the REST AdapterConnection to an Integration

    3 Map data between the triggerconnection data structure andthe invoke connection datastructure.

    Mapping Data of Using Oracle Integration CloudService

    4 (Optional) Create lookups thatmap the different values used bythose applications to identify thesame type of object (such asgender codes or country codes).

    Creating Lookups of Using Oracle Integration CloudService

    5 Activate the integration. Managing Integrations of Using Oracle IntegrationCloud Service

    6 Monitor the integration on thedashboard.

    Monitoring Integrations of Using Oracle IntegrationCloud Service

    7 Track payload fields inmessages during runtime.

    Assigning Business Identifiers for Tracking Fields inMessages and Managing Business Identifiers forTracking Fields in Messages of Using OracleIntegration Cloud Service

    8 Manage errors at the integrationlevel, connection level, orspecific integration instancelevel.

    Managing Errors of Using Oracle Integration CloudService

    Chapter 1Typical Workflow for Creating and Including an Adapter Connection in an Integration

    1-41

  • 2Creating a REST Adapter Connection

    A connection is based on an adapter. You define connections to the specific cloudapplications that you want to integrate. The following topics describe how to defineconnections.

    Topics

    • Prerequisites for Creating a Connection

    • Uploading an SSL Certificate

    • Creating a Connection

    • Editing a Connection

    • Cloning a Connection

    • Deleting a Connection

    Prerequisites for Creating a ConnectionYou must satisfy the following prerequisites to create a connection with the RESTAdapter:

    • If you are using one of the OAuth security policies, you must already haveregistered your client application to complete the necessary fields on theConnections page. The Basic Authentication and No Security Policy securitypolicies are exempted.

    Before a client application can request access to resources on a resource server,the client application must first register with the authorization server associatedwith the resource server.

    The registration is typically a one-time task. Once registered, the registrationremains valid, unless the client application registration is revoked.

    At registration time, the client application is assigned a client ID and a