Skip to content

advancedpricing/Xojo-Rest-Classes

master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 

Xojo REST Classes

A REST client framework for Xojo.

General Information

There is no standard for RESTful servers. As such, creating classes that work with a variety can be tricky and time-consuming, and tend to make you to work directly with JSON or other raw data. This framework attempts to make the job a bit easier by allowing you to create "messages" by subclassing the main class and implementing various events.

Installation

Open the enclosed harness project and copy-and-paste the REST Resources folder into your own project.

Important: Do not drag the REST Resources folder directly from the folder into your project. Xojo won't like it and will probably show all sorts of odd errors.

Basic Use

At its most basic, you need to create a "message" for each type of interaction with your RESTful server by subclassing RESTMessage_MTC. You might create one message that will login, another that will get a list of information, another to save some data. Each message must implement the GetURLPattern event (see below) and should implement the GetRESTType event.

If the REST server communicates with JSON, you can create properties in the message that correspond to the object keys. You can also use the ExcludeFromOutgoingPayload event to exclude a property or modify the key or value that will be included. In the CancelSend event you can cancel the send or change the URL, payload, or MIME type.

If you expect information back from the server in the form of JSON, you can create properties with the prefix of "Return", e.g., ReturnSuccess, ReturnFirstName, etc., and the return payload will be parsed into those properties. You can adjust the prefix through the Options (see below). You can also use the IncomingPayloadValueToProperty event to "massage" a value or store it elsewhere. For example, if you expect an image to be returned as Base64-encoded, you can use that event to decode it, store the resulting image in a ReturnImage property, then return True to prevent RESTMessage_MTC from processing the value further.

RESTMessage_MTC will attempt to deserialize a JSON object into a class. For example, suppose you expect JSON from the server that looks like this:

{
	"user" : {
		"FirstName" : "John",
		"LastName" : "Doe",
		"Age" : 33
	}
}

You can create a User class with properties FirstName As Text, LastName As Text, and Age As Integer, then create a property in the message ReturnUser As User. The class will automatically create an instance and fill in the properties for you.

The ResponseReceived event will let you know when the server has responded and, if you choose, let you deal with the payload directly.

There are times when it is not appropriate to have a single instance of a particular message. For example, if you need to save multiple records in a row. In those cases, you can create a RESTMessageSurrogate_MTC (see below) instead and send the message through it. The surrogate will raise all the events that the message would as if you had used AddHandler to map the message's events.

Details

This is a more detailed description of the RESTMessage_MTC class.

Events

Event Parameters Return Value Description
CancelSend ByRef url As Text,
ByRef httpAction As Text,
ByRef payload As Xojo.Core.MemoryBlock,
ByRef payloadMIMEType As Text
Boolean The last chance to cancel sending the message, or change the URL, HTTP action, payload, or MIME type for the send. Set the payload to nil to avoid any payload.
ContinueWaiting Boolean The message has exceeded the time specified in MessageOptions.TimeoutSeconds. Return True to let it continue waiting for another period. (See MessageOptions below.)
Disconnected The socket has disconnected.
Error msg As Text Some error has occurred during the connection.
ExcludeFromOutgoingPayload prop As Xojo.Introspection.PropertyInfo,
ByRef propName As Text,
ByRef propValue As Auto
Boolean A message property is about to be included in the outgoing payload. If it shouldn't be, return True. You can also change the property name that will be used as the JSON object key or the value.
GetRESTType RESTTypes See The GetRESTType Event below.
GetURLPattern Text See The GetURLPattern Event below.
IncomingPayloadValueToProperty value As Auto,
prop As Xojo.Introspection.PropertyInfo,
hostObject As Object
Boolean The incoming payload has a value that has been matched to a property of the message or one of the objects in its properties. Return True to prevent this value from being processed automatically, i.e., you will process it yourself.
ObjectToJSON o As Object,
typeInfo As Xojo.Introspection.TypeInfo
Auto An object in one of the message's properties is about to be serialized, but you may prefer to do it yourself. If so, return a Xojo.Core.Dictionary or an Auto() array. If you do not implement this event or return nil, automatic processing will proceed.
ResponseReceived url As Text,
HTTPStatus As Integer,
payload As Auto
The server has responded. The url contains the server's URL, HTTPStatus the raw code returned by the server, and payload as the best form that RESTMesstage_MTC could convert it into, i.e., Xojo.Core.MemoryBlock, Auto(), or Xojo.Core.Dictionary.
Setup The message object has been constructed. This is a good place to set the initial values of properties or MessageOptions.
SkipIncomingPayloadProcessing url As Text,
httpStatus As Integer,
ByRef payload As Auto
Boolean The server has responded with a payload. If you prefer the class not try to automatically parse it, return True.

The GetURLPattern Event

This event will let you specify the URL that will be used to connect to the server. It is raised each time you call Send.

You must return some value here.

The URL can be complete or may contain placeholders that represent properties within the message. For example, you need to get the weather in the zip code 99911 and the RESTful server requires the URL in the form:

http://www.someweathersite.com/api/get/zip/99911

You can create a property in your message subclass, ZipCode, and return the URL pattern like this:

http://www.someweathersite.com/api/get/zip/:ZipCode

RESTMessage_MTC will do the appropriate substitution. To send the message, you merely have to fill in the property and call Send.

Note: Properties that are part of the URL pattern will never be included in the outgoing payload.

The GetRESTType Event

RESTMessage_MTC defines a RESTTypes enum whose values either include or correspond to HTTP actions. Return the type appropriate for the message. As of v.1.0, these are:

Type
Unknown
Create
Read
UpdateReplace
UpdateModify
Authenticate
DELETE
GET
HEAD
OPTIONS
PATCH
POST
PUT

The uppercase types correspond directly to an HTTP action. The lowercase types are for convenience and will choose the proper action. For example, Read corresponds to the GET action.

Properties

Property Type Read Only Description
DefaultRESTType RESTTypes no The default REST type that will be used of the GetRestType event is not implemented.
IsConnected Boolean YES Returns True if the socket is currently connected.
MessageOptions M_REST.MessageOptions no Set the options for the message. See MessageOptions below.
MessageSerialNumber Int64 YES A unique number (within the session) assigned to each new instance of a message.
MessageTag Auto no Anything you wish to attach to a message. Does not get transmitted.
RESTType RESTTypes YES The REST type that is ultimately used for the message.
RoundTripMs Double YES The round-trip time, in milliseconds, from when the connection was initiated until a response received.
RoundTripWithProcessingMs Double YES The round-trip time, in milliseconds, from when Send was invoked until response processing was finished.

Methods

Method Parameters Returns Description
Disconnect Disconnect from the server immediately. If not connected, will do nothing.
Send (opt) surrogate As RESTMessageSurrogate_MTC Fill in the properties first, make sure the required events are implemented, then use this to send the message. Note: If the socket is already connected to the server, you will get an error. Check the IsConnected property or just call Disconnect first.

If a surrogate is specified, incoming events will be raised for this message in it too (see below).

MessageOptions

The MessageOptions will let you set certain parameters for the message. For example, if a message is expected to take longer to send or receive or you want to make sure the payload is never sent.

Property Type Default Description
AdjustDatesFromTimeZone Boolean False When encoded dates are sent or received, this determines if the time zone should be honored. If so, the date will be adjusted according to the local time zone.
ExpectedTextEncoding Xojo.Core.TextEncoding Xojo.Core.TextEncoding.UTF8 When the payload is received, it is usually as UTF-8. If the server expects or delivers something different, specify that here.
ReturnPropertyPrefix Text "Return" Any property in your subclass that starts with this prefix will never be included in the outgoing payload and will be cleared and, if possible, populated by the incoming payload. These properties may be a basic type like String, Text, or Integer, a Dictionary, Auto() array, or an object whose public properties correspond to the incoming JSON object.
SendWithPayloadIfAvailable Boolean True For any HTTP action other than GET, the class will attempt to construct and attach a payload using the properties of the message that (1) are not "Return" properties and (2) have not been included in the URL pattern. Set this to True to avoid that processing in all cases.
TimeoutSeconds Integer 5 Sets how long a message can wait before the ContinueWaiting event is raised.

RESTMessageSurrogate_MTC

The RESTMessageSurrogate_MTC class will act as a stand-in for a message after it is sent. Drag the class to your window and implement its events. When sending a message, use the optional second parameter to specify the surrogate.

Note: Events will be raised in the message first and then in the surrogate, except if an event returns a Boolean, returning True in the message will prevent the event from being raised in the surrogate.

Generally it doesn't make much sense to implement the same event in both the message and a surrogate. The surrogate is there for situations where dragging a single copy of a message to your window does not make sense, e.g., you need to quickly save multiple records in a row.

The parameters of each event match the parameters of the RESTMessage_MTC or Xojo.Net.HTTPSocket with the instance of the message as the first parameter in each case. This emulates using AddHandler to intercept the message's events.

You can also use the RESTMessage_MTC.MessageTag property to further identify an instance of a message.

The RESTMessageSurrogate_MTC has some additional properties and methods.

Methods

Method Parameters Returns Description
DisconnectAll Disconnect all of the outstanding messages
DisconnectMessage msg As RESTMessage_MTC Disconnect a single message
OutstandingMessages RESTMessage_MTC() An array of outstanding messages

Properties

Property Type Default Description
IsBusy Boolean Returns True if there are still outstanding messages

Contributions

Contributions to this project are welcome. Fork it to your own repo, then submit changes. However, be forewarned that only those changes that we deem universally useful will be included.

Who Did This?

This project was designed and implemented by:

  • Kem Tekinay (ktekinay at mactechnologies.com)

With special thanks to Advanced Medical Pricing Solutions, Inc. for making this possible.

Release Notes

1.2 (May 18, 2016)

  • Added RESTMessageSurrogate_MTC.Sent event.
  • Changed where ResponseReceivedMicroseconds is recorded.
  • Changed the parameter sender to message in RESTMessageSurrogate_MTC events.

1.1 (May 18, 2016)

  • Changed Options property to MessageOptions to prevent possible conflicts in subclasses.
  • Added MessageSerialNumber property.
  • Added RoundTripWithProcessingMs property.
  • Added MessageTag property.
  • Added RESTMessageSurrogate_MTC class.

1.0 (May 12, 2016)

  • Initial release.

About

A REST client framework for Xojo

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages