IBM i Devs Get Some REST with OData!

Programming - Other
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times


Adopt the OASIS Open Data Protocol to consistently publish and consume REST services.


In the article "Implement a Service-Oriented Architecture with REST APIs," I covered some basics about implementing a service-oriented architecture using REST APIs. In general, because the REST methodology doesn't have many standards regarding how to pass parameters, how to format the result data, etc., the implementation of these APIs can vary widely from vendor to vendor and developer to developer.


Originally started by Microsoft, the Open Data Protocol (OData) was devised in part as a means of having a standard input and output so that REST APIs based on OData would be consistent in their implementation. This standardization offers many benefits, including the ability to have a generic tool set connect to an OData source and consume the data. Just as ODBC paved the way as a standard for database access, OData is striving to be a popular standard for REST. OData's slogan is "The Protocol for REST APIs."

ODBC was great because it allowed client/server developers a standard way to access various database servers (such as DB2, SQL Server, Oracle, etc.) using the same coding practices. Because it was standardized and could access database metadata, various tools could interrogate the database server and build a list of available tables, columns, and other database objects to present to the user. The drawbacks with ODBC are that it's primarily Windows desktop- and server-based (with ports available on Linux), each database manufacturer needs to provide a driver, and the driver needs to be installed on each machine requiring database access. That's quite a bit of deployment maintenance.

With REST, ODBC's problems go away in that no special "middleware" providers/drivers are required and that use of Internet standards makes REST platform- and OS-independent. Building on REST's and ODBC's benefits, OData gives developers a standard way to "program" against an API, which increases productivity.

To illustrate some OData concepts, I'll be using the sample test services conveniently offered on to demonstrate some OData highlights (as I perceive they'd be of interest to the IBM i community). This article will merely be an introduction to OData, but interested parties can pursue much more at


Excel and Other Tools

To start, I'll defer some boring technical explanations in favor of showing how OData can be used by Excel. Microsoft Query (built into Excel) was one of the early tools that allowed users to access database data with ODBC. Excel 2013 allows users to directly query data from an OData service with similar benefits.

To access data from an OData API in Excel 2013, there are a few simple steps to follow: choose the Data ribbon > "From Other Sources" > From "OData Data Feed" as shown in Figure 1.



Figure 1: In Excel 2013, select an OData Data Feed as a source to import data directly from an OData API.

When prompted for the location of the OData data feed, simply paste in the URI to the sample Northwind Summary of Sales by Years test service:

This sample OData resource returns a list of orders, their ship dates, and their subtotalssimilar to a database query against an ERP orders table.

Excel gives the option to put in credentials, but the test service does not require them, so simply hit Next. You will be prompted to check the checkbox next to the Summary_of_Sales_by_Years table and then click Finish. The last Excel prompt allows you to place the OData feed as a table, pivot table, etc. at a specified location in the worksheet. Shown in Figure 2 is a partial result set with the OData feed formatted as a table (the Excel default):




























Figure 2: This abridged Excel data table was created directly from the Summary_of_Sales_by_Years OData feed.

This simple demonstration illustrates that OData APIs can offer data and logic to be consumed by a client similar to how ODBC clients access data and logic from a database server. But unlike ODBC, a driver installation is not required, knowledge of a particular database's data types and conventions is not required, and it can theoretically be accessed by any modern device or platform.

Incidentally, Excel 2010 and 2013 can also access OData and many other data feed types via the Power Query add-on.

In addition to Excel, many other tools and products can produce and/or consume an OData feed, including these:

  • SharePoint 2010 and later
  • Microsoft Azure
  • IBM WebSphere
  • SQL Server Reporting Services (reading data via the XML data source wrapped with a special query, producing an AtomPub feed with SQL Server 2008 R2 and later)
  • SQL Server 2012 and later Integration Services (using an OData source)
  • SAP NetWeaver Gateway
  • Microsoft Dynamics NAV ERP
  • eBay

As for OData-capable development environments:

  • Publish using .NET applications using WCF
  • Publish or consume using .NET applications created with LightSwitch
  • Publish or consume using Java applications using OData4j (a work in progress) or Apache Olingo.
  • Any applications that can take advantage of ODBC, OLE DB, or JDBC using a tool from RSSBUS that puts an ODBC (or OLE DB using ODBC)/JDBC wrapper around an OData feed
  • Others listed on the OData website, including options for iOS and Python

As applications become "service-oriented," it's easy to see the advantage of being able to share data among multiple products and programming languages with a standard protocol.

Keep in mind there are several versions of OData (with v4 as the latest) and you'll need to check with your tool/application provider to find out what version(s) are supported. As noted, Microsoft is the big supporter of OData but other major companies have contributed to the standard too.

The Ins and Outs of an OData Service

Back to the technical explanations, I'll describe here a little bit about how OData works.

URI Structure for Accessing an OData Service

The OData standard has laid out a specific URI syntax to support many features, as shown in Figure 3.


Figure 3: This is the anatomy of an OData URI (from

This URI structure should be familiar to web developers, particularly those working with HTTP-based services. The Query Options portion of the URI is where OData's features shine. Shown below are several examples of useful things that can be done with the OData URI, although this list certainly is not exhaustive. And the good news is you can paste these URIs in your browser to see how they work. Oddly enough, I'd stay away from Internet Explorer in these examples in favor of Chrome or Opera, where it's easier to see the raw data returned from the service.

URI Examples

Starting with the same base URI used in the Excel example above, pasting this in a browser will return a summary of all orders in the OData test system (with results returned as XML):

Building on the base URI, the OData specification offers several options for using the URI to filter, sort, compute, return a count, etc. To get a feel for OData's features, paste the next several URIs into your browser as well.

This next URI uses a filter query option to obtain all sales with a subtotal equal to a specific value of 654.06 (the M is used to indicate that the number is a decimal literal):$filter=Subtotal eq 654.06M

Of course, specifying the text $filter=Subtotal eq 654.06M is responsible for creating the filter. For another feature example, this URI selects only the top 10 sales entries, sorted by subtotal in descending order:$orderby=Subtotal desc&$top=10

When the host OData service supports it, client-side paging can even be implemented with the use of $skip and $top. (It is important to note that not every OData API is required to implement all of these featurers.)

In this next example, the first 50 rows of the result set are skipped and only 10 rows are returned, while $orderby ensures consistency in the rows returned.$skip=50&$top=10&$orderby=Subtotal desc

If you want to know how many rows will be returned by a service (which is useful when the client-side UI pages data), use the $count system query option:$count

One other notable feature is the $metadata operation that can be used to retrieve the metadata provided by an OData service root's resources:$metadata

Consider an excerpt from the metadata associated with the Summary_of_Sales_By_Quarter resource:

<EntityType Name="Summary_of_Sales_by_Quarter">


<PropertyRef Name="OrderID"/>


<Property Name="ShippedDate" Type="Edm.DateTime"/>

<Property Name="OrderID" Type="Edm.Int32" Nullable="false"/>

<Property Name="Subtotal" Type="Edm.Decimal" Precision="19" Scale="4"/>


It's easy to discern from this XML that three pieces of information are returned by the resource, including ShippedDate (DateTime), OrderId (Int32), and Subtotal (Dec(19,4)). Also the PropertyRef named OrderId indicates that a specific piece of information related to a single order id can be obtained by passing the order id in the URI as follows (using order id 10250 as an example):

This URI will return the sales only for the requested order id. If a resource's unique identifier is a string (such as an item number), it can be requested using a string value delimited by single quote. Each OData service is expected to have a unique identifier.

Further, the value of a specific property can be requested (in this case Subtotal). When the path segment contains $value, the raw value is returned (without XML or JSON formatting). This URI returns the plain value 1552.6000, the subtotal value of order id 10250:$value

One important thing to note is that the names in these queries are case-sensitive (Subtotal is not the same as SUBTOTAL). These subsequent URI examples can be modified to use the other resources available by this OData test service, such as querying the products that have a unit of measure ending with ml (milliliter):$filter=endswith(QuantityPerUnit,'ml')

Or query suppliers with a postal code starting with 99:$filter=startswith(PostalCode,'99')

For more information on OData URIs, including how to do computations, see the following links:

OData Responses: AtomPub (XML) and JSON

OData supports returning a response as the XML-based Atom Publishing Protocol (aka AtomPub) or JSON. Both of these formats are popular today and can be produced or consumed on the IBM i as discussed here. I'll show a few examples of the output formats in the next section(s). If you're unfamiliar with AtomPub, it’s the same XML you’ve seen show up in your browser if you've been reviewing the URI examples.

OData and CRUD Operations

OData is also geared for CRUD (CREATE, READ, UPDATE, DELETE) operations using HTTP verbs like DELETE (delete), POST (insert), PUT/PATCH (update), etc. This standardization gives clients a consistent way of updating data via an OData service.

An MSDN Blog titled oData and JSON payload examples shows a few examples of using JSON to perform CRUD operations using the Northwind sample OData service. Although you can't easily run these in a browser, the blog shows that it's quite easy to create the appropriate HTTP request programmatically.

This is an HTTP DELETE example from the blog that requests Product Id 200 be removed.


DataServiceVersion: 1.0;NetFx

MaxDataServiceVersion: 3.0;NetFx

Accept: application/json;odata=minimalmetadata


The random portion of the URL (after the V3) is temporarily assigned for the test service. Likewise, another JSON example is reproduced here using an HTTP POST to create a new product (with data supplied as JSON):


DataServiceVersion: 3.0;NetFx

MaxDataServiceVersion: 3.0;NetFx

Content-Type: application/json;odata=minimalmetadata

Accept: application/json;odata=minimalmetadata

Accept-Charset: UTF-8


Content-Length: 180

Expect: 100-continue






   "Name":"My new product from leo",





Of course, these data modification operations are possible only when the OData API supports it. (Otherwise, the danger of linking updateable ERP tables within a Microsoft Access database will be lived all over again!)

In summary, when supported by the service provider, OData queries come with the same benefits of database queries (available metadata; versatility with filtering, ordering, updating; and strongly typed results) with the advantage that OData, because it uses standards, doesn't require database-specific middleware.

DB2 Query to "Manually" Parse Atompub

Finally, let's not forget that good ol' DB2 can consume an OData source that returns AtomPub, which is, after all, XML. The following DB2 for i example query uses the new HTTP function HTTPGETBLOB to retrieve and parse the AtomPub data from the Summary_Of_Sales_By_Years test OData source (the same URI used in the Excel example).

Notice that the second parameter of HTTPGETBLOB is a request header containing an Accept key/value pair. This is required in order for the server to return a response. Note: DB2 HTTP functions require IBM i 7.1 with database group PTF level 23.  Finally, the XMLTABLE table function is used to shred the AtomPub XML returned from the service.




<header name="Accept" value="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" />

<header name="Accept-Encoding" value="gzip" />

</httpHeader>')) AS ODataSummary



SELECT Shred.*



'' AS "d",

'' AS "m",

'' AS "a",

'' AS "base"),

'$doc/a:feed/a:entry/a:content/m:properties' PASSING XML_DATA.ODataSummary AS "doc"


/* On i 7.2 you can use TIMESTAMP(0) */

ShippedDate TIMESTAMP     PATH 'd:ShippedDate',

OrderId     INT          PATH 'd:OrderID',

SubTotal   DECIMAL(19,4) PATH 'd:Subtotal'

) AS Shred


The results from this query are the same as the results shown from Excel in Figure 2. Basically, OData-aware tools examine the metadata and perform the above type of transformation automatically so the developer doesn't have to do the parsing!

The SQL query can be modified so that the service returns JSON instead of AtomPub XML. This can be done by simply changing the request header's "Accept" value:




<header name="Accept" value="application/json" />

<header name="Accept-Encoding" value="gzip" />

</httpHeader>') AS ODataSummary





The abridged JSON result looks like this:














Although probably not extremely useful with traditional IBM i languages such as RPG or COBOL, JSON is a frequently used format for client-side (i.e., browser) scripting in web-based applications. This is because the above result can be transformed into a JavaScript object that can be bound to controls on the web page, among other things.


OData provides a standard feature-rich protocol for REST APIs. These features include complex filtering, querying, sorting, paging, CRUD, and metadata retrievalto name a few. IBM i and other shops can benefit by adopting the OData protocol when creating REST APIs and consuming them.


Implement a Service-Oriented Architecture with REST APIs

JSON and XML Conversion in DB2 for i

Rev Up "i" Reporting with SQL Server 2008 Reporting Services

Michael Sansoterra is a DBA for Broadway Systems in Grand Rapids, Michigan. He can be contacted at



Support MC Press Online





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation.
    Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects.
    The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed.
    Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY the one package that solves all your document design and printing challenges on all your platforms.

    Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. How can you be sure you won’t miss important system events?
    Automate your message center with the Robot Message Management Solution. Key features include:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing.
    Manage your reports with the Robot Report Management Solution. Key features include:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.