Apex Restful Services 1964653

Embed Size (px)

Citation preview

How Do We Build Application Express?

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.1

Implementing RESTful Web Services with Oracle Application Express#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 2The following is intended to outline Oracles general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions.The development, release, and timing of any features or functionality described for Oracles products remains at the sole discretion of Oracle.#Copyright 2013, Oracle and/or its affiliates. All rights reserved.333 AgendaIntroduction to RESTREST ModelingAPEX RESTful Services Use CasesAPEX RESTful Services ArchitectureWalk through complete sample including:Resources using GET, PUT, POST, DELETE methodsTesting, debuggingAuthenticationQ & A

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 4Introduction to REST

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. ExamplesPublic services with RESTful APIs:Twitter, Netflix, Dropbox, Flickr, Amazon S3, ...Products or tools with RESTful APIsGlassfish Application Server Admin, Selenium WebDriver, ...RESTful FrameworksJersey (JAX-RS), Restlet, Restify, APEX RESTful Services, ...

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.What can REST do for you? Just another way to provide access to data/services.Just a small sample, there are many othersUse in products and tools may be internal rather than for 3rd party useThis talk focuses on how to define your own RESTful API/Service for either public or private use

6What is REST?REST stands for Representational State Transfer. (Sometimes written ReST)It describes an architecture for distributed information systemsFirst described in the 2000 doctoral dissertation Architectural Styles and the Design of Network-based Software Architectures by Roy Fielding.Its a description of how the Web works and why it works well

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.REST is an architectural style.By Web I mean the world wide web but also the specifications it is built on URI, HTTP, HTML etc (these are the technology foundations of the web).Term RESTful used for systems that follow the REST styleNot specific to web services.Roy was an author of the HTTP specification among other work on the early Web since 1993.The paper is about what makes the Web at large work not any particular web site/app/pageThe ideas that make up REST were developed along side the creation of the Web but different terms were used.Link to Roys paper and other resources given at the end.

7So what is REST?Client Server request responseStateless CachingLayeredCode on demand (optional)Uniform interface:Request response style operations on named resources through self descriptive representations where state changes are via hyperlinks

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.As a web developer (or API designer) what parts of the architecture are under your control?Client-server request response and layered are out of your control.Some may make recommendations about intermediariesThat leaves stateless, caching, uniform interface and code on demand There is nothing to enforce that you are using HTTP in a RESTful wayUniform interface is the most interesting (and distinguishing) point for web service design.

8Motivation and CharacteristicsHyper mediaOptimized for large grained static (cacheable) messagesInternet scalenot just size or geographymany independent organizationsExtensibility, flexibility, responsivenesshypermedia as the engine of application stateApplication state is 100% on the clientThe state or resources is persisted behind the servers

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Quote is from Roy Fieldings dissertation

9BenefitsScalability stateless, caching, gateways. Have more clients just add more servers or intermediaries.Performance caching, compression, incremental rendering, pre-fetchSimple client uniform interface means single client implementation can access any resourceSimple server no extra layers and no stateNo need for resource discovery due to hyperlinksReliability redundancy multiple serversSeparation of concerns and uniform interface allows clients and servers to change and be developed independently

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Stateless is key to scale and performance. Client isnt limited to talking to just one server. Server can reboot/be upgraded. No complicated session replication.The web browser isnt the only client (user-agent). Following REST means that your resource is available to spiders, wget and other tools, mashups etc.

10Uniform InterfaceThe REST Triangle:ResourcesMethodsRepresentations

ResourcesNouns UnconstrainedMethodsVerbs ConstrainedRepresentationsHyper Linked Constrained#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Roys paper treated hypermedia as separate from representations other places it is part of representations.

11Uniform Interfaces - ResourcesKey abstract conceptIdentified by a URIDistinct from underlying storageSemantics fixedValue may change over timeCan have multiple URIsCan have multiple representationsExamples:http://example.org/NewOrleans/traffic/10http://example.org/traffic/NewOrleans/I10http://foo.com/store/orders

ResourcesNouns UnconstrainedMethodsVerbs ConstrainedRepresentationsHyper Linked Constrained#Copyright 2013, Oracle and/or its affiliates. All rights reserved.The key thing is the set of all resources is unconstrainedA resource can be anything even the result of a calculation May be static or dynamicA simple/clean URI by itself != RESTResource is the target of a hyper link reference

12User Interface - MethodsConstrained setGET safePUT idempotentDELETE idempotentPOST not safe or idempotentApply to the resourceGET retrievePUT update (or create)DELETE deletePOST create sub resourceResponse codes 1xx, 2xx, 3xx, 4xx, 5xx

ResourcesNouns UnconstrainedMethodsVerbs ConstrainedRepresentationsHyper Linked Constrained#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Constrained on purpose so all clients can operate on all resourcesSafe means no side effects, the resource isnt changedIdempotent means repeatable with the same resultsHEAD is another method it is like GET but only returns the headersThere are a few others some in the webdav space and PATCHNew methods would have to be widely useful to many/all resources and understood by clients, servers, and intermediariesOften related to CRUD database operations but not an exact mappingWith post the created resource is named by the server

13User Interface - RepresentationsNot the actual resourceConstrained set Self-descriptivemedia type (Content-Type)text/htmlapplication/jsonIncludes metadataUnderstood by all componentsMay be for humans, machines or bothNegotiated

ResourcesNouns UnconstrainedMethodsVerbs ConstrainedRepresentationsHyper Linked Constrained#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Set of representations is constrained but more frequently extended than methods. For example application/json was added recentlyComponents are clients/browser (user-agent), web servers (origin server), gateways, proxies etc.Typically think of the response but representations can also be in the request (for PUT and POST) but understood media types more limited.Can think of representations as data typesSelf-descriptive means well defined semantics for all the parts of the message that client, server and everything in between can know about. Also the metadata tells you what type the message is and what you can do with it i.e. cache etc. Negotiation: not back and forth: client says what it can accept using Accept header (list with preference (q)). Server picks best it can supply. Server says what it returned in Content-Type headerRemember: You cant trust the client validate inputsRobustness principal: be liberal in what you accept, be conservative in what you send

14REST Modeling - How to design a RESTful API

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. REST ModelingIts different from: Object modeling Entity Relationship modelingResources are the key abstractionWhat are the resourcesWhat methods does each supportWhat representation(s) to useRelationships via linking

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.REST modeling should be easier for people with database background compared with OO background- already have fixed set of operations SELECT INSERT etc.

16REST Modeling - ResourcesStart by identifying the resourcesSimilar to thinking about entities but...Resources are not result sets (rows and columns)They are documentsTwo main typesCollectionsItems

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Think about what data the client needsThe resources may contain multiple sets of data.They tend to be large grained rather than fine grainedCould be a mix of items and collectionsA single table may have multiple resources. Think about how database views are used.

17REST Modeling - URIsHuman readable (not necessary but it helps)Tends to form a hierarchyUse the query part appropriatelyUse to search, filter, or possibly specify a modeIdentification of the resource is better in the path(preferred) http://example.com/orders/100234http://example.com/orders?id=100234Dont make them verbs!(bad) http://example.com/accounts/addaccount

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Consistent well organized URIs helpsThere are syntax rules for web URIs scheme, authority, path, query, fragment (last 3 are in the domain of your design)I see no problem with hackable or guess able URIs this means that given a few examples the user could guess (with a good chance of being right) about what other URIs might work.Identifying entities: numbers, guids, natural keysDont change URIs needlessly. Consider keeping old ones around.Think before changing URIs consider keeping the old ones around

18REST Modeling - RepresentationsThe usual suspects:text/htmlapplication/xmlapplication/jsonapplication/x-www-form-urlencoded (for input: PUT, POST)And others: images: svg, jpg, png etc., text/css, text/javascriptHow many does each resource need?Remember it is all about hyper media. Include links.

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.If the semantics/content changes from one rep to another it should be a different resource.If representation doesnt include URIs then must document how client can form URIs from other embedded identifiers

19REST Modeling - MethodsBut its not that simple

RESTCRUDSQLGETReadSELECTPOSTCreateINSERTPUTUpdate or CreateUPDATE or INSERTDELETEDeleteDELETE#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 20RESTCRUDSQLBut GETReadSELECTKeep it safe. Make sure there are no side effectsPOSTCreateINSERTAlso for other non-safe, non-repeatable changesPUTUpdate or CreateUPDATE or INSERTKeep it repeatable with same results (idempotent)DELETEDeleteDELETEKeep it repeatable with same results (idempotent)REST Modeling - Methods#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 21REST Modeling - MethodsThe difference between POST and PUT is in the meaning of the request URIFor PUT the URI is the resource that will be created or updatedFor POST the URI is the container of the resource that will be created. The server gets to assign a URI to the resourceConditional GETOptimistic concurrency for PUTUse method response codes appropriately

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Dont make up response codes in your message that HTTP already hasOptimistic concurrency for put: If-unmodified-since header and 412 precondition failed response code

22APEX RESTful Services Use Cases

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. Example Use CasesCreating a native mobile application using same database as corresponding APEX web applicationIntegration with back office operationsData collectionSynchronizationConfiguration managementProvide data persistence for a static single page web appYou have some interesting data you want to share with the world

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 24Reasons for using APEX RESTful ServicesImplement resources close to the dataLeverage your experience with PL/SQLMake use of existing logic in packagesUse existing APEX workspace and APEX Listener

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 25ConsiderationsAPEX Listener is requiredKeep up with the latest version Demos were done using version 2.0.3Authentication is needed for most real world situationsOAuth2 and APEX application authentication are supportedWhen making REST calls from a browser, either:Serve the calling web page from the same origin, orUse a modern browser that supports cross origin requests (CORS)Another option is to make the call from the server

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.WRT web apps that need data from web services, For SOAP or other protocols there was no choice but to have the server act as client to the remote serviceWith REST and ajax/xhr there is the possibility for the client to call the remote service directly.Doing REST from the server is less efficient. When the RESTful service is on the same instance as the APEX app it doesnt make much sense to call from the server. Often dynamic actions are a better choice.

26APEX RESTful Services Architecture

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. Architecture DiagramClientAPEX ListenerAPEXBuilderAPEXMetadata#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Client: browser, mobile, desktop, server, anything that talks HTTPAPEX Listener: is the core: request routing, URI parsing, all default behaviorAPEX Builder SQL Workshop for editing the RESTful service definitionsAPEX Metadata persistence for RESTful service definitionsAll processing happens in either the Listener or in your resource handlers

28Definition metadataRESTful Service Module Resource TemplatesHandler

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 29What the Listener does for youRequest dispatchingJSON generation for simple GET requestsPaginationLower cases column namesNull values are omittedGenerating JSON linksSimple JSON parsing, form data parsingException and error handling and responses (HTML)

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Cant easily support query parameters. Also no built-in support for matrix parameters because {param} must match somethingFor default JSON generation you dont get full control over the output.A . or .. prefix can be used in generating link URIsJSON parsing cant handle nested objects or arrays.You can get around any of these limitations with a little more effort.It also does authenticationEntity tag handling, cache control headers

30AuthenticationFirst party authenticationStandard APEX authenticationMust be in same workspaceThird party authenticationOAuth2Authorization code flowImplicit grant flow

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.First party means the API/service is uses its own authentication. APEX RESTful web services leverages the authentication used by APEXJust need to set the Apex-Session header with the app ID and session IDThird party means the API/services lets a third party authenticate the user. The third party just tells the service the user is who they say they are.OAuth2 is a complex protocol with many options and flows. Listener supports just two flows.In the end it comes down to sending an Authorization header with an access tokenThis is all explained well in the restful_services_devguide that comes in the listener zip download

31Handler Interface - InputsPagination control :page_size, :page_offset, :row_offset, :row_countFor authenticated requests :current_userParameters from the URI template become bind variablesRequest entity :content_type, :bodyRequest entity A simple JSON object is parsed and creates a bind variable for each property. A x-www-form-urlencoded body is parsed and creates a bind variable for each parameter.Any HTTP request header can be mapped to a bind variableSpecial pseudo headers from listenerOWA environment OWA_UTIL.GET_CGI_ENV

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.Some of this information is not fully documented currently.Currently best source of information is restful_services_devguide that comes in the listener zip download

32Handler Interface Inputs continuedSpecial pseudo headers from ListenerX-APEX-BASE the base URL of the requestX-APEX-PATH the path of the request relative to the baseX-APEX-CHARSET the character set of the request bodyX-APEX-METHOD the HTTP method used to make the requestX-APEX-PREFERRED-CONTENT-TYPE - from parsing the Accept HTTP request, identifies the MOST preferred content type that the client would like to receive

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.These pseudo headers are made available as bind variables just like normal request headers

33Handler Interface - OutputsAny HTTP response header can be mapped to a bind variableOWA context: htp.p etc.Special pseudo headers for ListenerX-APEX-STATUS - Specifies the numeric HTTP status code to generate for the responseX-APEX-FORWARD - Specifies the location of a resource that Listener should return as the response to this request.

#Copyright 2013, Oracle and/or its affiliates. All rights reserved.These pseudo headers are made available as bind variables just like normal response headers

34APEX RESTful Services Sample Walk Through

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. Example RESTful Service ModuleUses the tables from the APEX Sample Database ApplicationDEMO_CUSTOMERS, DEMO_PRODUCT_INFO, DEMO_ORDERS, DEMO_ORDER_ITEMSAPEX version 4.2.2, Listener 2.0.3Uses pl/json open source JSON libraryYou need to install this library to use the samplehttp://pljson.sourceforge.net/

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 36Common Patternemployes/GET - Retrieves list of all employees.POST - Create a new employee.

employes/{empno}/GET - Retrieves details for a specific employee.PUT - Updates the specific employee.DELETE - Deletes the employee.

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 37Testing TipsUse APEX RESTful Services Test Client (resttest.html)Use Firebug or developer tools to examine HTTP requests and responsesLook at Error-Reason headerDo initial browser testing from same origin Browsers hide error information when going cross originAnother Java based test tool: rest-client from WizTools.org

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 38Reference Material

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. REST ReferencesRESTful Web Services, by Leonard Richardson and Sam Ruby, available from OReilly Media at http://oreilly.com/catalog/9780596529260/Wikipedia: http://en.wikipedia.org/wiki/Representational_State_TransferThe source: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm mostly chapters 5 and 6A nice 14 minute video introduction: http://www.youtube.com/watch?v=YCcAE2SCQ6kHTTP spec: http://tools.ietf.org/html/rfc2616URI spec: http://tools.ietf.org/html/rfc3986JSON format: http://json.org/Other specs like HTML, XML etc. from w3.org

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 40APEX RESTful Services ReferencesApplication Express on OTN http://otn.oracle.com/apex The example module TBDAPEX RESTful Service Test Client TBDRESTful Services Dev Guide (restful_services_devguide.html) in the Listener download zip file doc folder

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. 41

@vuvarovs#Copyright 2013, Oracle and/or its affiliates. All rights reserved.42

#Copyright 2013, Oracle and/or its affiliates. All rights reserved. #Copyright 2013, Oracle and/or its affiliates. All rights reserved.44