Mostrando entradas con la etiqueta Web Services. Mostrar todas las entradas
Mostrando entradas con la etiqueta Web Services. Mostrar todas las entradas

jueves, 17 de septiembre de 2015

XML vs JSON Based Web Services: Which is the Best Choice?

XML vs JSON Based Web Services: Which is the Best Choice?

Many mobile applications can get by without ever having to exchange information over the web, but if you're looking to build data-driven mobile applications, sooner or later you're going to have to communicate with a remote server. There are many different ways of accomplishing this goal. Some approaches are succinct and lightweight, while others are woefully inefficient and data-heavy. For mobile devices, which may be bound by a monthly data cap and slow connectivity speeds, we want to be as lightweight and efficient as possible.

Problems with HTML

In a perfect world, we'd have web services for every bit of data we'd ever want to consume, but sadly that's not the case. In one particular project here at Segue, we were reduced to having to submit form posts and scraping the HTML result. Imagine the impact this has on a mobile device. The string manipulation involved in parsing down the resulting HTML required a solid amount of coding. HTML can be heavy; it contains data we don't need, including images and markup language that are of no significance to us as pure data consumers. HTML is long because it contains many characters other than pure content, which translates to slow transfer speed and eats into monthly data transfer limits. It’s is also dynamic and prone to change (as if you haven't already discovered this), and will eventually destroy your parsing routine, which is the process of whittling down the entire HTML string into its useable components using string manipulation functions.

The Advantages of Web Services

A way to overcome the limitations of HTML is to use web services. For those who don't know, a web service can be thought of as a function call to a remote server and offers very specific functionality. Web services exist all over the web and many are open to the public. If you're fortunate, you might find one that meets your data requirements. If not, you could always build and host one yourself. The advantage of web services is that they are focused on a particular set of data, so you don't have to filter out information that is of no use to you. For example, say you wanted a weather forecast. You could call a web service and pass in a date and expect to get a resulting forecast for the date you submitted. This means we are dealing with a small set of data specifically focused on our need, which equals a smaller data size and faster transmission speed. However, not all web services are created equal. The breadth of various technical differences between web service types is too broad to tackle in a single blog post, but we will discuss the difference in return formats, because they can have a measurable impact on speed.

Return Formats

In my experience, I've encountered two primary web service return formats: XML and JSON.Extensible Markup Language (XML) has long been a popular way to structure data using familiar markup language. It is both human and machine readable and is very similar in appearance to HTML. It follows a set of standards for data communication over networks between devices and is iteratively parseable. One advantage of consuming data in this format is its structure. Data can be added or removed from the result set, but it will often exist in a predictable format so you don't have to worry about your parsing routine breaking when the data changes over time. Despite its advantages, one drawback of XML is its size, because it contains many characters strictly related to formatting. When downloading data to a mobile device, it would be ideal to just obtain the relevant content instead of data related to content formatting. This is where JSON comes in.
JavaScript Object Notation (JSON) is a text-based data interchange format derived from theJavaScript scripting language. It is formatted as key-value pairs and is often lauded as being a lower-overhead to XML because it focuses more on content and less on formatting. This works to our advantage when we want to keep data interchange packets as compact as we viably can. Now to be fair to XML, it is possible to format it in specific ways or use compression to make it comparable in size to JSON, but generally I find JSON to be much smaller in size and therefore preferable to XML.
One final observation (geared toward iOS since that is the particular platform for which I develop) focuses on how we process the two formats on the device once information has been returned from the web service. Parsing XML in iOS can be a bit tedious as it involves implementing a handful of NSXMLParserDelegate methods to iterate through the XML code. This can require a significant amount of coding. On the other hand, if a JSON object is returned from a web service we can convert it directly into native objects such asNSDictionary or NSArray. These objects can be archived and we can access data elements as key-value pairs without having to implement any delegate methods or iterate through the result data. This equates to a measurable increase in speed and efficiency. For my money, JSON is absolutely the way to go for mobile device data consumption.
What to Read Next:
json
JSON es un formato de intercambio ligero que al igual que el XML puede ser  leído fácilmente  y es independiente de la plataforma, esta basado en sub conjunto de javascript por esta razón puede ser convertido a javascript rápidamente y por lo tanto es ideal para aplicaciones Web basadas en AJAX, pero la ventaja de JSON sobre AJAX es que es capas de representar la misma información en un formato mas ligero que el XML y por lo tanto es mas rápido de transportar y consume menos ancho de banda.
Un ejemplo de un objeto serializado con ambos formatos:
Con XML:
<Product>
<ProductID>1</ProductID>
<ProductCode>p_1</ProductCode>
<ProductName>a Product 1</ProductName>
</Product>
Con JSON:
{“ProductID”:1,”ProductName”:”a Product 1″}
Como podemos ver con JSON nos ahorramos una cantidad de información que no es necesaria que viaje en las peticiones que hacemos por ejemplo a un Web services. Así que veamos que necesitamos para que nuestro servicio Web se comunique a través de JSON.
-Primero necestaremos que en nuestro archivo web.config contiene la sección correspondiente del objeto ScriptJsonSerializationSection
<section name=”jsonSerialization”
type=”System.Web.Configuration.ScriptingJsonSerializationSection,System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″
requirePermission=”false” allowDefinition=”Everywhere”/>
-Segundo configuraremos la clase de nuestro servicio Web para que use el atributo [System.Web.Script.Services.ScriptService]
[System.Web.Script.Services.ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
[WebMethod]
public string GetServerTime()
{
string serverTime =
String.Format(“The current time is {0}.”, DateTime.Now);
return serverTime;
}
}
-Tercero indicaremos a nuestro Web method el formato que utilizara con el atributo [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetServerTime()
{
string serverTime =
String.Format(“The current time is {0}.”, DateTime.Now);
return serverTime;
}
Si queremos enviar objetos ya serializado en JSON para ser consumidos desde javascript podemos hacerlo de la siguiente manera
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(yourObject.GetType());
//Creo un memory stream
MemoryStream ms = new MemoryStream();
//serializo el objeto en el Memory Steam
serializer.WriteObject(ms, yourObject);
//Convierto el objeto serializado en un string
string jsonString = Encoding.Default.GetString(ms.ToArray());
//close the memory stream
ms.Close();
Para deserializar un objeton tambien es muy sencillo, imaginemos que recibimos el objeto persona
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Persona));
ms.Position = 0;
Persona p = (Persona)ser.ReadObject(ms);
Con la utilizacion de JSON vemos como podemos disminuir de manera considerable la cantidad de datos que enviamos y recibimos al servidor lo cual convierte a nuestra aplicacion en un sistema mucho mas escalabre y que respondera mucho mejor ante una sobre carga de usuarios.

JSON Web Services

Legacy:JSON Web Service

Home > Integrate > Web Services > Other > Legacy:JSON Web Service

1 Overview

The ability to describe sets of data in JSON format is a natural extension to the JavaScript language. ServiceNow supports a web service interface that operates on the JSON object as the data input and output format.
Note
Note: The JSON Web Service feature is replaced by JSONv2 starting with the Dublin release.

The JSON web service is provided by a platform-level processor similar to the services for SOAPWSDLCSV, Excel, and XML. Like those services, the JSON service is triggered by the standalone JSON URL parameter. For example:
https://<instance name>.service-now.com/mytable.do?JSON
Having the JSON object available as a data format for web services means that you can create (insert), update, and query any data in the ServiceNow platform using the JSON object format, and get results in the JSON object format.

1.1 Security

Like all other HTTP-based web services available on the platform, the JSON web service is required to authenticate using basic authentication by default. The user ID that is used for authentication is subjected to access control in the same way as an interactive user.

2 Activating the Plugin

An administrator must activate the JSON Web Service plugin to configure a JSON web service.

3 JSON Object Format

The JSON object is built in two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

In its simplest form, a JSON object is just a comma delimited set of name/value pairs. For example:
{"name one":"value one","name two":"value two"}
The following is a sample of a single record array of incidents in JSON:
{"records":
  [{"closed_by":"",
    "__status": "success",
    "category":"inquiry",
    "escalation":"0",
    "state":"1",
    "location":"",
    "reassignment_count":"0",
    "time_worked":"",
    "order":"0",
    "due_date":"",
    "number":"INC0010180",
    "upon_approval":"proceed",
    "sla_due":"2010-03-04 22:51:49",
    "follow_up":"",
    "notify":"1",
    "business_stc":"0",
    "caused_by":"",
    "rejection_goto":"",
    "assignment_group":"d625dccec0a8016700a222a0f7900d06",
    "incident_state":"1",
    "opened_at":"2010-02-23 22:51:49",
    "wf_activity":"",
    "calendar_duration":"",
    "group_list":"",
    "caller_id":"",
    "comments":"",
    "priority":"3",
    "sys_id":"fd0774860a0a0b380061bab9094733ad",
    "sys_updated_by":"itil",
    "variables":"",
    "delivery_task":"",
    "sys_updated_on":"2010-02-23 22:51:49",
    "parent":"",
    "active":"true",
    "opened_by":"681b365ec0a80164000fb0b05854a0cd",
    "expected_start":"",
    "sys_meta":"System meta data",
    "watch_list":"",
    "company":"",
    "upon_reject":"cancel",
    "work_notes":"",
    "sys_created_by":"itil",
    "cmdb_ci":"",
    "approval_set":"",
    "user_input":"",
    "sys_created_on":"2010-02-23 22:51:49",
    "contact_type":"phone",
    "rfc":"",
    "approval_history":"",
    "activity_due":"",
    "severity":"3",
    "subcategory":"",
    "work_end":"",
    "closed_at":"",
    "close_notes":"",
    "variable_pool":"",
    "business_duration":"",
    "knowledge":"false",
    "approval":"not requested",
    "sys_mod_count":"0",
    "problem_id":"",
    "calendar_stc":"0",
    "work_start":"",
    "sys_domain":"global",
    "sys_response_variables":"",
    "correlation_id":"",
    "sys_class_name":"incident",
    "short_description":"this was inserted with python",
    "impact":"1",
    "description":"",
    "correlation_display":"",
    "urgency":"3",
    "assigned_to":"",
    "made_sla":"true",
    "delivery_plan":""}
  ]
}
The following is a record array of incident responses with an error.
{
    "records": [
        {
            "__error": {
                "message": "Invalid Insert into: incident",
                "reason": "Data Policy Exception:  Short description is mandatory "
            },
            "__status": "failure",
            "active": "true",
            "activity_due": "",
            "approval": "not requested",
            "approval_history": "",
            "approval_set": "",
            "assigned_to": "",
            "assignment_group": "d625dccec0a8016700a222a0f7900d06",
            "business_duration": "",
            "business_stc": "",
            "calendar_duration": "",
            "calendar_stc": "",
            "caller_id": "",
            "category": "inquiry",
            "caused_by": "",
            "child_incidents": "0",
            "close_code": "",
            "close_notes": "",
            "closed_at": "",
            "closed_by": "",
            "cmdb_ci": "",
            "comments": "",
            "comments_and_work_notes": "",
            "company": "",
            "contact_type": "phone",
            "correlation_display": "",
            "correlation_id": "",
            "delivery_plan": "",
            "delivery_task": "",
            "description": "",
            "due_date": "",
            "escalation": "0",
            "expected_start": "",
            "follow_up": "",
            "group_list": "",
            "impact": "3",
            "incident_state": "1",
            "knowledge": "false",
            "location": "",
            "made_sla": "true",
            "notify": "1",
            "number": "INC0010001",
            "opened_at": "2013-07-23 18:01:17",
            "opened_by": "6816f79cc0a8016401c5a33be04be441",
            "order": "",
            "parent": "",
            "parent_incident": "",
            "priority": "5",
            "problem_id": "",
            "reassignment_count": "0",
            "reopen_count": "0",
            "resolved_at": "",
            "resolved_by": "",
            "rfc": "",
            "severity": "3",
            "short_description": "",
            "skills": "",
            "sla_due": "",
            "state": "1",
            "subcategory": "",
            "sys_class_name": "incident",
            "sys_created_by": "admin",
            "sys_created_on": "2013-07-23 18:01:17",
            "sys_domain": "global",
            "sys_id": "a96479343cb60100a92ec9a477ba9e45",
            "sys_mod_count": "0",
            "sys_updated_by": "admin",
            "sys_updated_on": "2013-07-23 18:01:17",
            "time_worked": "",
            "upon_approval": "proceed",
            "upon_reject": "cancel",
            "urgency": "3",
            "user_input": "",
            "watch_list": "",
            "work_end": "",
            "work_notes": "",
            "work_notes_list": "",
            "work_start": ""
        }
    ]
}

3.1 Response Status

In both of the code samples, the JSON object returned elements that describe the status of the GlideRecord response and whether the response included an error.

3.1.1 status

The status element uses this syntax:
"__status": "<value>",
where <value> is success or failure.
When the status element returns failure, the error element is added to identify the error and reason.

3.1.2 error

The error element uses this syntax:
"__error": {
:"message": "<error value>",
:"reason": "<reason value> "
:}
where <error value> is the error message text and <reason value> is the reason the error was triggered.

4 Setting the Number of Rows Returned

The following system property controls how many rows JSON returns with each query.
PropertyDescription
glide.processor.json.row_limitSpecify the maximum number of rows a JSON query returns.
  • Type: integer
  • Default value: 250
  • Location: Add to the System Properties [sys_properties] table

5 Action Parameters

Action parameters are separate and different from data parameters because they specify the action to take when the JSON object parameter is POSTed or when it is part of an HTTP GET. The parameters can also be specified as a field in the supplied JSON object. They have the effect of triggering an action in the case of sysparm_action, or filtering the results of an update or query in the case of sysparm_query.

5.1 sysparm_action

Following are the valid values for sysparm_action and the corresponding actions triggered by the API.
Data Retrieval
Method SummaryDescription
getKeysQuery the targeted table using an encoded query string and return a comma delimited list of sys_id values.
getRecordsQuery the targeted table using an encoded query string and return all matching records and their fields.
getQuery a single record from the targeted table by specifying the sys_id in the sysparm_sys_id URL parameter, and return the record and its fields.

Data Modification
Method SummaryDescription
insertCreate one or more new records for the table targeted in the URL.
insertMultipleCreate multiple new records for the table targeted in the URL.
updateUpdate existing records for the table targeted in the URL, filtered by an encoded query string.
deleteRecordDelete one record from the table targeted in the URL by specifying the sys_id in the sysparm_sys_id URL parameter.
deleteMultipleDelete multiple records from the table targeted in the URL, filtered by an encoded query string.

5.2 sysparm_query

Specify an encoded query string to be used in getgetRecordsupdate or deleteMultiple sysparm_action values.

5.3 sysparm_view

Specify a form view to customize the return values for get and getRecords function calls. When a view is specified, the query returns only the fields defined in this view, including referenced values. If there is no view name, or if the view name is not valid, then the query returns all field names that are marked active in the dictionary.

5.4 sysparm_sys_id

Specify a target sys_id during a get or delete function call (sysparm_action value).

5.5 displayvariables

Set this boolean value to true during a get or getRecords function call to retrieve all variables attached to this record.

6 Data Retrieval API

You can query for data by issuing an HTTPS GET request to the platform. By default, a GET request is interpreted as a get function if a sysparm_sys_id parameter is present. Otherwise, it is interpreted as agetRecords function. You can also specify a URL parameter sysparm_action=get. Query responses are always encapsulated by a records hash of records, where each individual record's values are themselves hashed by field name.

6.1 Return Display Value for Reference Variables

When you are getting a record from a get or getRecords function, all the fields associated with that record are returned. The fields are often reference fields that contain a sys_id for another table. The base system behavior is to return the sys_id value for those fields. To have the display value for the field returned, use one of these options:
  • Add the property glide.json.return_displayValue to the system properties, and every JSON request will return a display value for a reference field.
  • Add the parameter displayvalue=true to the JSON request URL and JSON requests with that parameter will return a display value instead of the sys_id for a reference field. The JSON request URL would look like this:
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=getRecords&sysparm_query=active=true^category=hardware&displayvalue=true
  • Add the parameter displayvalue=all to the JSON request URL, and JSON requests with that parameter will return a display value and the sys_id for a reference field. The response element name for the display value field will be prefixed with dv_, for example, dv_caller_id.

6.2 Return Display Variables

Use the displayvariables parameter to return an array of variables associated with a service catalog item record when using a get or getRecords function. The variables are expressed hierarchically. A variable container has the container's variables in its children field.
To get display variables, add the parameter displayvariables=true to the JSON request URL. The JSON request URL would look like this:
https://<instance name>.service-now.com/sc_req_item.do?JSON&sysparm_action=getRecords&
sysparm_query=active=true^short_description=Laptop%20preconfigured%20for%20developers&displayvariables=true
White space has been added to the following example for clarity:
"variables":[{"children":null,"name":"asset_tag","order":1300,"question_text":"Asset Tag","type":6,"value":""},
{"children":[{"children":null,"name":"ste1","order":-1,"question_text":"Test","type":6,"value":"test"}],
"name":"Test one","order":-1,"question_text":"Testing","type":0,"value":null},
{"children":null,"name":"","order":200,"question_text":"Please specify an operating system","type":3,"value":"Windows XP"},
{"children":[{"children":null,"name":"create_item","order":1000,"question_text":"Create an Inventory Item?","type":7,"value":""}],
"name":null,"order":-1,"question_text":"Options","type":0,"value":null},
{"children":null,"name":"serial_number","order":1100,"question_text":"Serial Number","type":6,"value":""},
{"children":null,"name":"hard_drive","order":100,"question_text":"What size hard drive do you want?","type":3,"value":"60 GB"},
{"children":null,"name":"name","order":1200,"question_text":"Name of new inventory item","type":6,"value":""},
{"children":null,"name":"company","order":1400,"question_text":"Manufacturer","type":8,"value":""}]

6.3 Controlling the Order of Records

You can control the order that records appear in the JSON response. To set an order, use the ORDERBY or ORDERBYDESC clauses in the URL encoded query. For example,sysparm_query=active=true^ORDERBYnumber^ORDERBYDESCcategory filters all active records and orders the results in ascending order by number first, and then in descending order by category. For more information, see Listing Values in Order.

6.4 getKeys

Get the sys_id of multiple records by specifying an encoded query string in the sysparm_query parameter.
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=getKeys&sysparm_query=active=true^category=hardware

6.5 get

Get a record directly by specifying the sys_id in a sysparm_sys_id parameter.
https://<instance name>.service-now.com/incident.do?JSON&sysparm_sys_id=9d385017c611228701d22104cc95c371
Optionally, you may also specify the sysparm_action parameter:
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=get&sysparm_sys_id=9d385017c611228701d22104cc95c371

6.6 getRecords

Get all records by specifying an encoded query string in the sysparm_query parameter.
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=getRecords&sysparm_query=active=true^category=hardware

7 Data Modification API

To modify the JSON web service, issue an HTTPS POST request to the platform. The HTTP POST must contain a sysparm_action parameter indicating the type of action to be performed, with the incoming JSON object post in the body.
Note
Note: The content-type of the POST should be application/json. It cannot be application/x-www-form-urlencoded or <tt?multipart/form-data</tt>.

7.1 insert

Create a new record in ServiceNow. The JSON object has to be POSTed as the body (content-type is usually application/json, although not enforced). The response from the record creation is a JSON object of the incident that was created.
For example, posting the following JSON object:
{"short_description":"this is a test","priority":"1"}
to the following URL:
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=insert
creates an incident.
Optionally, you may also specify the sysparm_action in the JSON object. The parameter inside the JSON object takes precedence over the URL parameter. For example:
{"sysparm_action":"insert","short_description":"this is a test","priority":"1"}

7.1.1 Inserting Multiple Records

To create multiple new records in ServiceNow, the input JSON object for the insert function must be an array. The response from the record creation is a JSON object of the incidents that were created. For example, the following JSON object posted to one the following URLs creates two incidents. Note the fields described as an array value for the records field.
{"records":[{"short_description":"this was inserted with python using JSON 1", "priority": "1 - Critical", "impact":"1", "caller_id":"Fred Luddy"},
            {"short_description":"this was inserted with python using JSON 2", "priority": "1 - Critical", "impact":"1", "caller_id":"Fred Luddy"}]}
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=insert
https://<instance name>.service-now.com/incident.do?JSON&sysparm_action=insertMultiple

7.2 update

Update a record or a list of records filtered by an encoded query string specified by the sysparm_query URL parameter. The JSON object has to be posted as the body (content-type is usually application/json, although not enforced). The response from the record creation is an array of JSON objects representing the records that were updated.
For example, posting the following JSON object:
{"short_description":"this was updated with python", "priority": "3", "impact":"1"}
to the following URL:
https://instance_name.service-now.com/incident.do?JSON&sysparm_query=priority=3&sysparm_action=update
updates all incidents with priority 3, and sets the values specified by the JSON object.

7.3 deleteRecord

Delete a single record, identified by a sysparm_sys_id parameter, from the targeted table. The parameter may be encoded in the input JSON object or given as a URL parameter.
Posting:
{"sysparm_sys_id":"fd4001f80a0a0b380032ffa2b749927b"}
to the following URL:
http://instance_name.service-now.com/incident.do?JSON&sysparm_action=deleteRecord
deletes the incident record identified by the sys_id fd4001f80a0a0b380032ffa2b749927b.

7.4 deleteMultiple

Delete multiple records from the targeted table, filtered by an encoded query string specified in the sysparm_query URL parameter. The filter may also be encoded in the input JSON object.
Posting:
{"sysparm_query":"short_description=this was updated with python"}
to the following URL:
http://instance_name.service-now.com/incident.do?JSON&sysparm_action=deleteMultiple
deletes all incident records where the short_description field contains the value this was updated with python.

zen consultora

Blogger Widgets