# Writing the API function code

The xxxapi.c file contains the service API functions. Each API function calls a corresponding SPI function and logs any errors returned using the Natural Access error macros.

This topic presents:

- Application API command flow

- Calling the SPI function

- Error handling macros

- Example API function

## Application API command flow

The following illustration shows the flow of a command initiated by an application API call:

Service API call to SPI function

## Calling the SPI function

The signature of an SPI function is typically identical to that of its associated API function with one exception. The SPI function contains an additional parameter to indicate the invoker of the SPI function (an application or another service). Since an API function is only invoked by an application, each API function calls the SPI function using CTA_APP_SVCID.

## Error handling macros

To ensure consistent error handling for all Natural Access services, the service API function should use the Natural Access error macros for reporting API errors. The Natural Access error macros expand to calls to dispApiError.

The macro CTAAPIERROR is called with an error code and the API function name:

#define CTAAPIERROR (ctahd, err) dispApiError((ctahd), (err),\
funcname, NULL)

CTAAPIERRORINFO also includes an additional information string to further qualify the error:

#define CTAAPIERRORINFO (ctahd, err,info)dispApiError((ctahd),\
(err), funcname, info)

The Natural Access error macros must be called by API functions when an error is returned so that the dispatcher can invoke the application registered error handler and log a trace message to the ctdaemon.

To use the error macros, the service API function must include a call to the macro CTABEGIN with the function name. This macro defines a local variable funcname that stores the function name that is passed to dispApiError when the other error macros are invoked.

## Example API function

tik service

<<<< excerpt from tikapi.c >>>>

/*------------------------------------------------------------
tikStartTimer
- tik service API function to start timer function on tik server
------------------------------------------------------------*/
DWORD NMSAPI tikStartTimer( CTAHD ctahd, TIK_START_PARMS *start)
{
DWORD ret ;
/* Needed by CTAAPIERROR */
CTABEGIN( "tikStart" ) ;
/* Call corresponding SPI function with CTA_APP_SVCID */
ret = tikSpiCmdStartTimer( ctahd, start, CTA_APP_SVCID ) ;
/* Log error on failure */
if ret != SUCCESS )
{
CTAAPIERROR( ctahd, ret ) ;
}
return ret ;
}