Your First CGI Program

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

It never seems to fail; I go to see new clients and find them locked into the old green-screen metaphor. They don't want a GUI because of reason X, Y, or Z. Then, after a few months, corporate management suggests that they want their information available through the Web for easier access.

Suddenly, everything GUI is the technology du jour. Specifically, a Web browser interface is needed, and of course, since the clients haven't done anything with CGI/Web programming or GUI, they go off on a research mission.

The first mistake they make is to expect to use IBM's WebFacing for everything. They soon realize WebFacing is a great technology that's good for a very specific style of applications: flat, green-screen apps that don't use windows or pop-ups and don't stretch what you could do with a green-screen too far. For those old, System/36-style applications, WebFacing is a fine tool for those shops that do not have CGI programming skills. It is also good if you have someone on staff who can follow up on the basic conversion with customizations of the generated JSPs and/or JavaBeans. However, while WebFacing is not a bad tool, it's often abandoned once users see the unusual way the 5250 screen maps to a browser.

The next mistake people make is to consider installing the WebSphere Application Server (WAS). This adds a level of overhead to your system that you just don't need. In addition, you are pretty much stuck using WDSc's development environment to build to the WAS interface. WAS should be considered for huge applications where your entire corporation has committed to it, but for the small-to-medium size AS/400/iSeries/i5 shops, it is just too big (read: bloated) to deal with.

A few shops are choosing the right solution in my view, which is using CGI with RPG IV or JSPs. Both can be hand-coded or automatically generated by one of the third-party tools. JSPs are OK, but this is, after all, RPG Developer, so of course I prefer the RPG IV/CGI approach.

Writing a CGI program in RPG IV requires that you learn the entire CGI process and then apply that knowledge to RPG IV. In addition, you need to learn the APIs that IBM includes with OS/400 to do CGI programming from within RPG IV.


The purpose of this article is not to teach CGI programming concepts, but to introduce you to the CGI APIs and help you build your first CGI program. IBM includes a set of APIs that provide CGI capability to RPG IV and other ILE-targeted languages. ILE C/400 has CGI capability built in to the language, and there are also several add-on libraries that provide clean and direct CGI support from within C. Therefore, the CGI APIs are not required if you use C or C++.

IBM includes seven APIs for CGI programming. They are summarized in the table below.

APIs for CGI Programming
API Name
Gets a value from the CGI environment
Changes a value in the CGI environment
Reads a string from the standard input device (i.e., read data sent to a CGI program from an HTML form)
Writes a string to the standard output device (i.e., write to the Web browser)
Converts URL-encoded string to an externally described data structure
Parses the data from an HTML form
"Utilities" to create a full HTTP response

About the Environment

IBM quietly added the UNIX "environment" to OS/400 when they added PASE to the machine. The environment is used by CGI (not exclusively, however) to store and retrieve data. The easiest way to understand the "environment" is to think of it as a positionless data area. The environment allows you to store data in it and retrieve data from it by "variable" name. For example, to store the next available customer number in the environment, you could specify it as a parameter of the QtmhPutEnv, in the following syntax:


NEXTCUST is the "variable" or identifier that is assigned to the value, and 12345 is the value that is saved or assigned to NEXTCUST. Later, when you need to retrieve the next customer number, you call the QtmhGetEnv API and ask it to return the value for NEXTCUST, and it kindly returns 12345 to your program. This beats using a data area by at least a factor of 1000.

About Standard In/Out

To send data to a Web browser, you need to route the data through what's called "standard output," which is different from a 5250 green-screen process. Standard output is where commands send their data to; this is UNIX-style I/O. Standard output can be rerouted (similar to an OS/400 file override) to a file or another device. The standard output device is used to send data to the Web browser from RPG IV and other high-level languages (HLLs). IBM provides the QtmhWrStout API to send data through standard output. Likewise, IBM also provides an API to read data from the Web browser: QtmhRdStout, which reads from the standard input device, yet another UNIX-style I/O device.

Copying Data from HTML Forms to Database

IBM also provides a really cool API called QtmhCvtDB. If you have an HTML form that an end user has entered data into and you want to move that data to an externally described data structure, you can use this API. You specify the data structure name and a database format file. The API uses the format file to convert the data from the HTML form into the externally described data structure.

The QtmhCvtDB API is very popular with inexperienced CGI programmers who have written only one or two CGI programs, but they quickly learn that it is really a highly specialized API and widespread use of it is probably not going to save the RPG CGI world.

Parsing Data from HTML Forms

A better and more complex solution to moving data from an HTML form into fields in your RPG CGI program is to use the QzhbCgiParse API. This API is actually a port of a C routine written for another platform. QzhbCgiParse is very complex, and you need to not only read IBM's documentation on it, but also find the source for it on the Internet and read that as well. You might ask, why read the API's source code? Once you read IBM's documentation on QzhbCgiParse, you'll understand why I suggest that you need to go elsewhere for information on this API.

QzhbCgiParse is a favorite tool of experienced CGI programmers. You'll find most generated RPG CGI code uses it, and the two most popular CGI add-on libraries have great wrappers for it as well.

CGI Add-On Libraries

For several years, there has been a little-known service program available from IBM to help simplify CGI RPG programming. This library has moved around on the Web from place to place over the last few years and is, as of this writing, available at IBM's Easy400 Web site. I used this add-on library for years and have programmed dozens of in-production RPG CGI applications using it.

Last year, questions were raised as to the future availability of this add-on library. I made an offer to IBM to make that library available for free from my own Web site, but those negotiations ended up going nowhere. At that point, I had to make a decision. I decided that hoping IBM would continue to make the add-on library available in the future wasn't a good business decision, so I created my own CGILIB add-on library using the RPG xTools as the underlying infrastructure. Since then, IBM has made the add-on library available at the URL mentioned above.

Today, when I need to create an RPG CGI program, I use CGILIB, an add-on service program for RPG IV. CGILIB contains several helper procedures that make CGI programming simple. The good news is, it is also a free add-on service program. It does, however require that the RPG xTools are installed on your system.

My First RPG CGI Program

To create a CGI program with RPG IV, you need to learn about the CGI process, the CGI method, the CGI program logic flow, API syntax, and standard input/output. With CGILIB, you don't need to know any of that. You just write regular old RPG IV code and embed CGILIB's add-on subprocedures. For example, assume an HTML page has a form on it that requires that the end user enter a name and address. Using CGILIB, you can retrieve the name and address information easily. For example:

     C                   callp     cgiInit()
     C                   eval      CMPNAM = cgiGetVar('COMPANY'
     C                   eval      CNTNAMEcgiGetVar('CONTACT')
     C                   eval      ADDR1  = cgiGetVar('ADDR1')
     C                   eval      CITY   = cgiGetVar('CITY')
     C                   eval      ST     = cgiGetVar('STATE')
     C                   eval      EMAIL  = cgiGetVarL('EMAIL')
     C                   eval      PHONE  = cgiGetVarDec('PHONE'

The first line calls the CGILIB initialization routine. This procedure initializes some variables and creates a couple of user spaces in QTEMP. The other lines retrieve the value of each variable entered into the HTML form by the end user. The example uses the cgiGetVar() procedure to read each field's value and store it in your own fields in your RPG CGI program. The cgiGetVar() procedure is a wrapper for the IBM QzhbCgiParse API. It goes directly to the source for the data, and it works very fast.

The last line is a helper routine that returns the data as numeric (decimal). Normally, all HTML form data is returned to you as plain text (i.e., character form only). It is up to you to convert it to numeric if necessary. Since there is no reason to make you do additional work, CGILIB has helper procedures that do the conversion automatically for you. So cgiGetVarDec() returns the value from the HTML form as a decimal. The following is a list of cgiGetVar() subprocedure variations:

cgiGetVar() Subprocedure Variations
API Name
Retrieves a value from an HTML form
Retrieves the number of occurrences of an individual HTML form field
Retrieves a value from an HTML form field and converts it to uppercase
Retrieves a value from an HTML form field and converts it to lowercase
Retrieves a value from an HTML form as a decimal value
Retrieves a value from an HTML form as an integer

In my next issue of RPG Developer, I will continue this thread and illustrate the output capability of RPG CGI. That is, I will illustrate how to write to the Web browser.

Bob Cozzi is a programmer/consultant, writer/author, and software developer of the RPG xTools, a popular add-on subprocedure library for RPG IV. His book The Modern RPG Language has been the most widely used RPG programming book for nearly two decades. Along with others, he speaks at and runs the highly popular RPG World, a conference for RPG programmers.

Robert Cozzi

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.

MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale



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.


  • 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



  • 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.