1. In the TutorialPublish server module, select the GetContact server routine:
Srvroutine Name(GetContact) Response(*HTTP #context)
Endroutine
2. Replace it with the code below.
3. Compile the server module.
Srvroutine Name(GetContact) Response(*HTTP
#context)
Define_Com Class(#PRIM_IOC.StringWriter)
Name(#StringWriter)
Define_Com Class(#PRIM_JSON.Writer) Name(#Writer)
Textwriter(#StringWriter)
/* Get the {ContactId} parameter which is the
Key to the xContacts table. */
If
(#Context.Request.PathParameters.TryParseAsInt32( "ContactId",
#xContactIdentification ))
/* Read the First and Last Name from the
database with the supplied key */
Fetch Fields(#ContactFields)
From_File(xContacts) With_Key(#xContactIdentification)
/* If found, write
out the values and send a successfull response */
If_Status
Is(*OKAY)
#Writer.TextWriter <=
#StringWriter
#Writer.BeginObject
#Writer.WriteString(
#xContactLastName, "LastName" )
#Writer.WriteString( #xContactFirstName,
"FirstName" )
#Writer.EndObject
#Context.Response.HttpStatus :=
200
#Context.Response.ContentType :=
"application/json"
#Context.Response.ContentString :=
#StringWriter.Text
Return
Endif
Endif
/* When not
found, send a 404 not found response. */
#com_owner.MakeBadRequestResponse
Context(#context) Path(#Context.Request.Path) Resourcename("Get /Contact/{id}")
Status(404) Additionalmessage("Invalid ContactID requested or ContactID does not
exist in table xContacts")
Endroutine
API Details – Key Points
As seen in the Define API video, the ContactId was defined in the path.
To get the parameter value into field #xContactIdentification:
#Context.Request.PathParameters.TryParseAsInt32(
'ContactId', #xContactIdentification )
To retrieve the first and last name from xContacts table:
Fetch
Fields(#ContactFields) From_File(xContacts) With_Key(#xContactIdentification)
To write the response values:
#Writer.BeginObject
#Writer.WriteString(
#xContactLastName, 'LastName' )
#Writer.WriteString(
#xContactFirstName, 'FirstName' )
#Writer.EndObject