Sunday, February 7, 2016

Fix some errors when working with REST API

Response Code: "400 BadRequest"
Response Message: "A node of type 'PrimitiveValue' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was expected"

or

Response Message: {“odata.error”:{“code”:”-1, Microsoft.SharePoint.Client.InvalidClientQueryException”,”message”:{“lang”:”en-US”,”value”:”The property ‘__metadata’ does not exist on type ‘SP.User’. Make sure to only use property names that are defined by the type.”}}}

or

Response Message: {“error”:{“code”:”-1, Microsoft.SharePoint.Client.InvalidClientQueryException”,”message”:{“lang”:”en-US”,”value”:”An entry without a type name was found, but no expected type was specified. To allow entries without type information, the expected type must also be specified when the model is specified.”}}}

This error is very common and used to get from result of REST API in workflow or JSON. The special thing of REST API in SharePoint is no having the same as formatted of command structure.

See example:

Upload file to library

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/Add(url='file name', overwrite=true)
method: POST
body: contents of binary file
headers:
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-type: "application/json;odata=verbose"
    content-length:length of post body

Create a list

url: http://site url/_api/web/lists
method: POST
body: { '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100,
 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The difference of those structure is a number of parameters and position of parameters. Some parameters must be transfer by query string and some of properties is passed from body of message. Assume that to upload the file name with the path is too long (over 256 characters), it will throw the error.

In the body of message, sometime we must define the variable named "parameters" to pass them to REST API and sometime it is not necessary. The most important thing is to understand of formatted snippet of REST API for separately command.

 

Example above also throws the error and I have a final solution is to remove the "parameters" from body of message. If you set the method is PUT, that means you must provide all properties of endpoint and X-HTTP-Method = MERGE is not affected. If you need to set some properties and leave some properties to be default or not set, you must set the method to POST and define X-HHTP-Method = MERGE

See the result



Good luck!



1 comment:

John Frag said...

I recommend you to check out Long Path Tool program