When developing an OData service for searching for contact persons by name, I came across a scenario where the name contains the special character ' (single quote character). As an example, the user would like to search for contact persons with the last name O'Reilly.

The URL encoding of the single quote character is %27. First I just tried the following:
https://servername/sap/opu/odata/SAP/Z_CONTACT_PERSON_SRV/ContactSet?$format=json&$filter=substringof(%27O%27Reilly%27,%20SearchText)

This lead to an error with HTTP status code 400 and the message "Invalid token detected at position &" with exception /IWCOR/CX_DS_EXPR_SYNTAX_ERROR.

As you might already have guessed, the issue is that %27 is used to enclose the search string. When adding a single %27 within the search string, the parser of the $filter expression gets confused.

The solution is to escape the single quote by adding a single quote before it:
https://servername/sap/opu/odata/SAP/Z_CONTACT_PERSON_SRV/ContactSet?$format=json&$filter=substringof(%27O%27%27Reilly%27,%20SearchText)

If you would like to comment on this post, please head over to SAP Community.