Implement Put API

1.     In the TutorialPublish server module, select the PutContacts server routine:

Srvroutine Name(PutContacts) Response(*HTTP #context)
Endroutine

 

2.     Replace it with the code below.

3.     Then compile the server module.

 

Srvroutine Name(PutContacts) Response(*HTTP #context)

 

Define_Com Class(#PRIM_JSON.Document) Name(#Document)

Define_Com Class(#PRIM_JSON.Array) Name(#RequestArray) Reference(*DYNAMIC)

Define_Com Class(#PRIM_IOC.StringWriter) Name(#StringWriter)

Define_Com Class(#PRIM_JSON.Writer) Name(#Writer) Textwriter(#StringWriter)

 

* Validate the incoming content

#Document.LoadFromString( #Context.Request.Content.FormVariables<"*POSTDATA">.GetText )

 

* If there is no RootNode then the content is either non existent or no valid JSON format.

If (#Document.RootNode *Is *Null)

#Com_Owner.MakeBadRequestResponse( #Context, "Invalid Request, Document is null or it doesn't contain valid JSON. ", #Context.Request.Path 500 )

Return

Endif

 

* Instantiate the requested content as a JSON array

#RequestArray <= #Document.RootNode *As #PRIM_JSON.Array

 

If (#RequestArray *Is *Null)

#Com_Owner.MakeBadRequestResponse( #Context, "Invalid Request, Document Root Node is null or not a valid JSON Array.", #Context.Request.Path 500 )

Return

Endif

 

* Iterate each object in the Array and update the database accordingly

For Each(#object) In(#RequestArray)

 

#xContactIdentification := #object<"ContactID">.AsInt32

#xContactFirstName := #object<"FirstName">.AsString

#xContactLastName := #object<"LastName">.AsString

 

Update Fields(#UpdateContact) In_File(xContacts) With_Key(#xContactIdentification) Issue_Msg(*YES)

 

Leave If(#IO$STS <> OK)

 

Endfor

 

If_Status Is(*OKAY)

 

* All good, write out an informational message response

#Writer.TextWriter <= #StringWriter

 

#Writer.WriteString( ("Contacts Updated Successfully.") )

 

#Context.Response.HttpStatus := 200

#Context.Response.ContentType := "application/json"

#Context.Response.ContentString := #StringWriter.Text

 

Else

 

* Get the message issued by the Update and send a bad response

Use Builtin(GET_MESSAGE) To_Get(#ReturnCode #Message)

 

* Send a 404 not found response

#Com_Owner.MakeBadRequestResponse Context(#Context) Path(#Context.Request.Path) Resourcename("Invalid or no Contact ID ") Status(#HttpStatus) Additionalmessage(#Message)

 

Endif

 

Endroutine