Search Veni, Vidi, Vici

Special Characters in REST ListItem Metadata

I’m constantly trying to remember which way to encode content when making calls to the server while developing client side solutions for SharePoint.  Usually it’s some form of JavaScript’s encodeURI()/encodeURIComponent() functions… but this latest one gave me a bit of trouble until I finally figured it out which encoding to use and, almost as important, when to apply it.

When making RESTful calls to update or create data in a SharePoint list you must include the “__metadata” (two underscores followed by ‘metadata’) property in the information object you send on the data property of the call.  If you have a list with the internal name “Clients” and your data property object is called “item” then you would do something like the following:

item.__metadata: {"type": "SP.Data.ClientsListItem"}

However, if your list’s internal name has any spaces or special characters you must encode the list name in this property differently than you’re encoding it for the REST url which (most often) uses the list’s display name.  But what type of encoding you may ask… the full ASCII hex value plus a leading and trailing underscore is the answer.  So for instance:

List with internal name “Client_Information” would look like:
item.__metadata: {"type": "SP.Data.Client_x005f_InformationListItem"}

and a list with internal name “Client Information” would look like:
item.__metadata: {"type": "SP.Data.Client_x0020_InformationListItem"}

Here’s one reference to an ASCII chart but there’s hundreds available.

Now, when you’re making your REST call, in the URL you would use the lists display name (because that’s what getbytitle expects) and it would look something like:

<SharePoint site URL>/_api/web/lists/getbytitle('Client_Information')/items(1)

or

<SharePoint site URL>/_api/web/lists/getbytitle('Client Information')/items(1)

In the case of the list item with these special characters you can wrap the list name in the afore mentioned encodeURIComponent() function, something like…

var url = "<SharePoint site URL>/_api/web/lists/getbytitle('" + encodeURIComponent('Client Information') + "')/items(1)"

but in general I find it works just fine without it.

Hope the clarification helps someone else.

UPDATE: And now that I shared all that insight, guess what?!  You don’t need any of it.  Check out Marc’s blog post where he explains the “odata” setting in your request header!

Happy Coding!