Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I HTML encode response of my Web API

I am designing a Web API which returns JSON as the content-type, the response body could contain characters like ', ", < and >, they are valid characters in JSON. So, my question is should I do HTML encode for my Web API response body or should I leave this task to HTML client who is consuming my Web API?

like image 684
Shuping Avatar asked Aug 20 '13 02:08

Shuping


People also ask

Should JSON be HTML encoded?

So if you are intending to write JSON into the html as part of Javascript (a very common use), you need to encode JSON contents to HTML unfortunately. It's much better to avoid this and download data separately. those are some very good points!

Why do we need to encode HTML?

HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.

What is encoding in API?

The Encoding API provides a mechanism for handling text in various character encodings, including legacy non-UTF-8 encodings. The API provides four interfaces: TextDecoder , TextEncoder , TextDecoderStream and TextEncoderStream . Note: This feature is available in Web Workers.

When should I use Htmlencode?

Any time you are trying to output data that could include untrusted html, you should use HTMLENCODE . Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign ( > ), with HTML entity equivalents, such as &gt; .


Video Answer


1 Answers

No; you must not.

You must only escape data if and when you concatenate it into a structured format.

If you return JSON like { "text": "Content by X &amp; Y" }, anyone who reads that JSON will see the literal text &amp;.
It will only work correctly for extremely broken clients who concatenate it directly into their HTML without escaping.

In short:

Never escape text except when you're about to display it

like image 56
SLaks Avatar answered Oct 09 '22 01:10

SLaks