Thursday, 1 March 2012

my first REST resource

<- Previous Contents Next ->

Tutorial on REST: First REST Resource(cfc)

In first part we saw a simple example on REST to start off the things. So moving forward I will give another very simple example and will explain it.

  1. Every component and every function acts as a REST resource(if you are publishing them). 
  2. A new attribute in cfcomponent 'restpath' OR 'rest' defines if a component can be published as a REST resource. Either of these should be present. 
  3. Attribute 'httpmethod' should be there in cffunction tag or cfcomponent tag. 'httpmethod' in cffunction tag overrides the one in cffcomponent tag. To publish/expose a function as resource, this attribute is necessary. Valid values for this are 'GET', 'POST', 'PUT', 'DELETE', 'OPTION', 'HEAD'. 
  4. Similar to 'httpmethod', 'restpath' can also be used in cffunction tag but it doesn't overrides the value of 'restpath' in cffcomponent tag , instead it appends to it. So if you want to call this function(resource), you need to give both the restpath's in URL. Check helloWorld.cfm's second http call for clearer picture
  5. Keeping other things simple like 'access=remote'(required for REST/WEB services) and 'returntype=string', lets see how can we call this service. 
Note: After writing a cfc(at-least one) in webroot, you need to register the folder(in which that REST cfc is present) as REST application, otherwise you will not be able to call any resource. Please check previous chapter for that.

  1. Considering that you registered this application with name 'IIT', the URL to access first resource(function HelloWorld) will be:
  2. So to access that resource all you need to do is, use cfhttp tag and call this URL. Keep in mind that method in cfhttp tag will match to the httpmethod present in function.
  3. Similarly to call the second Resource in cfc(function HiWorld), the URL will be:
  4. To call this from a cfm you need to call this URL using cfhttp tag with httpmethod as get.

how the URL works:

Breaking the URL for better understading
  1. - protocol//ip:port/
  2. rest/ - Compulsary string to call a REST resource. You can change this 'rest' string in server.xml and restart the server for changes to take effect.
  3. Examples/ - Mapping name you give to register an application using Administrator or restInitApplication method(Check next example for this) .
  4. HelloWorld/ - RestPath to call a resource. This was given as 'restpath' attribute in cfcomponent level.
  5. HiWorld/ - If your function also has a restpath then after giving a restpath for your component you need to give restpath for function also to call that function.

<- Previous Contents Next ->