cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Did you know you can set a signature that will be added to all your posts? Set it here! X

REST API Overview and Examples

No ratings

Overview

REST stands for representational state transfer and is a software architectural style common in the World Wide Web. Anything with a RESTful interface can be communicated with using standard REST syntax. ThingWorx has such an interface built-in to make viewing and updating Thing properties as well as executing services easy to do independently of the Web UI.

 

How to Use REST API

The ThingWorx REST API is entirely accessible via URL using the following syntax:

   rest_syntax.png

(Precision LMS. Getting Started With ThingWorx 5.4 (Part 1 of Introduction to ThingWorx 5.4). PTC University. https://precisionlms.ptc.com/viewer/course/en/21332822/page/21332905.)

 

The above example shows how to access a service called “GetBlogEntriesWithComments” found on the “ThingWorxTrainingMaintenanceBlog” Thing. Notice that even though this service gets XML formatted data, the method is type “POST” and “GET” will not work in this scenario (Further reading: https://support.ptc.com/appserver/cs/view/solution.jsp?n=CS214689&lang=en_US).

 

In order to be able to run REST API calls from the browser, one must allow request method switching. This can be enabled by checking the box “Allow Request Method Switch” in PlatformSubsystem (Further reading: https://support.ptc.com/appserver/cs/view/solution.jsp?n=CS224211&lang=en_US).

 

Access REST API from Postman

Postman is a commonly used REST client which can ping servers via REST API in a manner which mimics third party software. It is free and easy-to-use, with a full tutorial located here: https://www.getpostman.com/docs/

 

In order to make a request, populate the URL field with a properly formatted REST API call (see previous section). Parameters will not automatically be URL-encoded, but right-clicking on a highlighted portion of the URL and selecting EncodeURIComponent encodes the section.

 

Next click the headers tab. Here is where the content-type, accept, and authorization are set for the REST call. Accept refers to which response format the REST call is expecting while content-type refers to the format of the request being sent to the server. Authhorization is required for accessing ThingWorx, even via REST API (see previous section for examples authenticating using an app key, but in Postman you can also use Basic Auth using a username and password)

 

In Postman, there is also ample opportunity to modify the request body under the Body tab. There are several options here for setting parameters. Form-data and x-www-form-urlencoded both allow for setting key value pairs easily and cleanly, and in the latter case, encoding occurs automatically (e.g. “Hello World” becomes %22Hello%20World%22). Raw request types can contain anything and Postman will not touch anything entered except to replace environment variables. Whatever is placed in the text area under raw will get sent with the request (normally XML or JSON, as specified by content-type). Finally, binary allows for sending things which cannot normally be entered into Postman, e.g. image, text, or audio files.

 

 

REST API Examples

 

 

  • Updating “MyProperty “with the value “hello” on “MyThing” using PUT: http://localhost/Thingworx/Things/MyThing/Properties/MyProperty?method=PUT&value=hello

    • In Postman, you can send multiple property updates at once via query body (in this case updating all of the properties, the string “Prop1” and the number “Prop2” on MyThing)
      • § Query: http://localhost/Thingworx/Things/MyThing/Properties/*
      • § Query Type: PUT
      • § Query Headers:
        • Content-Type: application/json
        • Authorization: Basic Auth (input username and password on Authorization tab and this will auto-populate)
        • § Body JSON: {"Prop1":"hello world","Prop2":10}
      • Note: you can also specify multiple properties as shown, but only update one at a time in Postman by utilizing the browser syntax given above

 

 

    • It is easier to pass things like XML and JSON into services using Postman. This query calls “MyJSONService” on “MyThing” with a JSON input parameter
      • § Query: http://localhost/Thingworx/Things/MyThing/Services/MyJSONService
      • § Query Type:
      • § Queries Headers:
        • Accept should match service output (text/html for String)
        • Content-Type: application/json or
        • Authorization: Basic Auth (input username and password on Authorization tab and this will auto-populate)
        • Body JSON: {"InputJSON":"{\"JSONInput\":{\"PropertyName\":\"TestingProp\",\"PropertyValue\":\"Test\"}}"}
        • Body XML:{"xmlInput": "<xml><name>User1</name></xml"}

 

 

 

    • In Postman, more information can be passed into some queries via query body
      • § Query: http://localhost/Thingworx/Logs/ApplicationLog/Services/QueryLogEntries
      • Query Type: POST
      • Query Headers:
        • Accept: application/octet-stream or
        • Content-Type: application/json
        • Authorization: Basic Auth (input username and password on Authorization tab and this will auto-populate)
        • Body: {\"searchExpression\":\"\",\"origin\":\"\",\"instance\":\"\",\"thread\":\"\", \"startDate\":1462457344702,\"endDate\":1462543744702,\"maxItems\":100}

 

 

  • Uploading files to FileRepository type Things is a bit tricky as anything uploaded must be Base64 encoded prior to making the service call. In Postman, this is the configuration to used to send a file called “HelloWorld.txt”, containing the string “Hello World!”, to a folder called “FolderInRepo” on a FileRepository named “MyRepo”:

 

    • Query: http://localhost/Thingworx/Things/MyRepo/Services/SaveBinary
    • Query Type: POST
    • Query Headers:
      • Accept: application/json
      • Content-Type: application/json
      • Authorization: Basic Auth (input username and password on Authorization tab and this will auto-populate)
      • Body: {"path" : "/FolderInRepo/HelloWorld.txt", "content" : "SGVsbG8gV29ybGQh"}
        • Notice here that the content has been encoded to Base64 using a free online service. In most cases, this step can be handled by programming language code more easily and for more challenging file content

 

 

 

 

Comments

A concise, well organized summary of useful information with links to additional details. Thanks, Tori.

Is a restart of TW required after changing “Allow Request Method Switch” in PlatformSubsystem or does it take effect immediately?

Can you give a brief synopsis on why the default setting is unchecked and the security consequences of changing the setting to checked.

If I need to change this setting on an on-premise platform inside a customer firewall I'll need to provide an explanation.

Hello Andy,

I am glad you liked this article, and I appreciate your feedback!

To answer your question, Allow Request Method Switch leaves you open to CSRF (Cross-Site Request Forgery) attacks. Essentially, once any window within a browser is authenticated for URL REST requests, then any Javascript/spam which may have accidentally been downloaded or activated in that same browser session could wreak havoc on the ThingWorx instance.

This setting is really best used for Dev environments or when you are quickly checking syntax of REST requests or checking items within Composer for development purposes.

The KCS article which details this is located here.

Thanks!

Tori

Its a great article but when i am trying to send json its working

Sorry, I don't understand your post. Is there some issue you are seeing?

sorry i wanted to say i am not getting how to send JSON through it dynamically..

if in json is present in my any folder updating automatically after specific time interval and i want to send it by the same time interval is it possible with postman and how to do it?

I found this doc based on your YouTube video.https://youtu.be/gorya9USTqU

It got saved at 480p resolution. That makes is all but useless to see. Is there any plan to upload in a higher resolution? I think the video content is great, but the resolution just doesn't work. Also please make sure you have any pertinent links (like this page) in the video description. It makes it a lot easier for the viewer to follow up on what you are covering. These things can be a pain in the neck, but really help the viewers.

Is there a way to directly receive property values of thing via REST API? When I call all properties or a specific property I always receive an array which also contains the complete field definition of the properties/property.

Hello, have you already tried calling GetPropertyValues? I think that may be what you are looking for, and it is accessible through the REST API. I believe it is a POST request though, and not a GET like one might think. I think the syntax would go something like: http://localhost/Thingworx/Things/UtilityThing/Services/GetPropertyValues?method=POST

 

Hope this helps!

Is there a way to set your own http response status code in a custom TWX service?

-

Version history
Last update:
‎Jan 10, 2024 07:36 AM
Updated by:
Labels (1)
Contributors