The more I use APIs, the more I realize how powerful they are, but learning to use them is a process; this article provides a first step.
IBM offers programmers incredible access to the IBM i operating system, but no single avenue is more extensive and powerful than the Application Programming Interface (API) library. So many APIs exist that IBM requires an entire website just to provide access to the documentation. In this article, I'll show you how I've been using this vast resource to advance my application programs.
We'll Begin at the End
Before we start working with specific APIs, I want to cover what might be the most powerful piece of the puzzle: the API error-handling process. For a large percentage of the APIs, IBM provides a very consistent yet flexible way to handle error conditions that supports three techniques, depending on your programming needs. Those three techniques roughly mirror the way we handle errors in CL programming:
- Just let the error happen (and halt the program).
- Monitor the error and ignore it.
- Handle the error with condition-specific programming.
Let's take a look at all of three of these in a specific circumstance. A very common task is to check to see whether an object exists. This is one of those system functions that can be executed either by a CL command or via an API, so it works very well to illustrate the point. Let's start with the appropriate CL code:
CHKOBJ OBJ(MYLIB/MYFILE) OBJTYPE(*FILE)
With this command, if the file MYFILE does not exist in library MYLIB, an error will occur. What happens next depends on what else you do in your program. If you provide no other programming, the program will halt, sending message CPF9801with the text "Object MYFILE in library MYLIB not found" to the user (or to the system operator in the case of batch jobs). The user can respond to the error message, and the program can continue (or not, depending on the response).
However, you can also do a couple of things to mitigate that hard halt. One is to just follow the CHKOBJ command with the following line of code:
By putting this statement immediately after the CHKOBJ, you will ignore the CPF9801 message. Because I specified CPF0000 (with the four zeros), we'll also ignore any other message starting with CPF. However, ignoring errors is often not a good idea, so let's see the third case:
CHKOBJ OBJ(MYLIB/MYFILE) OBJTYPE(*FILE)
MONMSG MSGID(CPF9801) EXEC(DO)
CRTPF FILE(MYLIB/MYFILE) RCDLEN(80)
In this case, we check for a specific error, and if it occurs, then we do something in response; in this case, if the file is not found, we create it. Because we coded the specific message ID (CPF9801) in the MSGID keyword, any other errors will actually halt just as if we hadn't coded a MONMSG at all. You can instead follow this with more MONMSG instructions to handle other errors and then finally with generic handlers such as MONMSG MSGID(CPF0000) to handle unexpected errors. Hopefully, this is just review; it's just meant to get us to the API programming. If you're unfamiliar with this subject matter, you can learn more about CL programming through books such as Ted Holt's masterpiece, Complete CL, available from our own wonderful MC Press.
Handling Errors in APIs
As I've said already, the majority of IBM i APIs use the standard API error technique. Notable exceptions include the UNIX-type APIs such as system and iconv, which use the errno value to indicate the error. I'll discuss that in a different article that will focus on the UNIX-type APIs. Today, though, we will review the standard API error structure. Let's take a look at just the API error structure itself. It has three variations:
*n int(10) inz(0);
*n int(10) inz(0);
dcl-ds ApiIgnore qualified;
BytPrv int(10) inz(8);
BytAvl int(10) inz(0);
dcl-ds ApiError qualified;
BytPrv int(10) inz(%size(ApiError));
BytAvl int(10) inz(0);
The third iteration (ApiError) is the most flexible; it is set up to return the error message data. If your command fails, the error message ID and message data will be returned in the MsgID and MsgDta fields, respectively, in the ApiError data structure. We'll look at that one in a moment. But first let's discuss ApiIgnore and ApiThrow. These are the shortcut structures; each is only eight bytes long. The first four bytes tells the API how much error information you want returned, while the second are used by the API to communicate whether an error occurred. If you pass zero in the first bytes (as is done in ApiThrow), then any error causes a halt. If, on the other hand, you pass a value of exactly 8 (eight), then an error will not cause a halt, but a non-zero value will be returned in the second four bytes. Please note that the subfields BytPrv (bytes provided) and BytAvl (bytes available) exist in both ApiError and ApiIgnore, which is why I use the qualified modifier. I'll leave it as a reader exercise to determine why I didn't specify qualified for ApiThrow.
Returning to ApiError, you'll see that it uses a different technique for the first value. The BytPrv field is initialized to the size of the overall ApiError data structure. This would change based on, for example, the length of the MsgDta field. And that's exactly what we use it for: to return a larger (or smaller) amount of message data. We'll see how all this works in the next section.
Calling an API
It's time to call an API. Two APIs exist that provide similar functionality to CHKOBJ. One is QSYCUSRA, which checks the authority, but for those cases when all you're doing is checking the existence of the object, QUSROBJD is a better fit. It simply retrieves the object description, but it returns an error if the object is not found. The prototype for the call is pretty standard: there's a data structure that defines the data returned, and a call. Here's the free-format definition:
dcl-ds OBJD0100 qualified;
dcl-pr QUSROBJD extpgm;
iDataLen int(10) const;
iFormat char(10) const;
iObjlib char(20) const;
iType char(10) const;
iError char(1) options(*varsize);
You see the OBJD0100 data structure, which contains the data that we'll be returning. Like many other APIs, the QUSROBJD API can return data in multiple formats. The format used is determined by one of the parameters passed into the API. In this case, the iFormat parameter identifies which format to use. Other formats return more data; you can see more about them and the QUSROBJD API in general on the IBM website. Today we're just going to focus on the last parameter in the prototype, iError.
Since we may pass parameters of different lengths to this API depending on the kind of error-handling we need, the correct prototype definition is to use options(*varsize) as part of the subfield definition. This causes the compiler to ignore the length check and basically allows you to pass any size of parameter. This means that you and the API have to somehow agree on the length of the parameter. In the case of the ApiError structure, it's done in those first four bytes that are initialized with %size(ApiError). So let's write the actual program that uses all of this:
OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiError);
OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiIgnore);
OBJD0100: %size(OBJD0100): 'OBJD0100': iObj+iLib: iTyp: ApiThrow);
*inlr = *on;
As you can see, after setting up the prototypes and structure, the code is actually very straightforward. You can refer to the website for a more in-depth explanation of the parameters that I need to pass in, but I can describe them briefly here. The first three identify the receiver variable: the variable itself, the size of the variable, and the format, OBJD0100. The next two are the input parameters for the actual object. The first is the standard IBM construct for a qualified object, which is the 10-character object name and the 10-character library name concatenated into one 20-character field. Next is the object type. Finally, we include the (optional) error-handling structure. I have three different calls using the same values, just with different error handling.
You can now copy all the code above into an RPGLE member and compile it and call the program to see how each works. The first uses ApiError, which returns the message ID and data. In fact, if I call the program with an object that doesn't exist, I can see the following data in ApiError when using the debugger:
APIERROR.BYTPRV = 96
APIERROR.BYTAVL = 36
APIERROR.MSGID = 'CPF9811'
APIERROR.RESERVED = '0'
1 'NOOBJECT QGPL
Each subsequent call acts differently. The second call returns nothing except the value 36 in the second parameter. This is the indication that an error occurred. And finally, the third call causes the error to be thrown back to the program, and I get a hard halt saying the call failed (as well as seeing the CPF9811 error in the joblog).
More to Come
Today's article is just an introduction to the universe of API programming. You can find a wealth of great information online, including the fantastic IBM System i APIs at Work book, also available here at MC Press. In upcoming articles, I'll be introducing you to other APIs, along with techniques I happily incorporated from the work of others, including Carsten Flensberg's incredible website, APIs My My My.