The Content-Type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type to detect what to do with it.

Answer from gen_Eric on Stack Overflow
🌐
Atlassian
developer.atlassian.com › server › crowd › json-requests-and-responses
JSON requests and responses
curl -i -u application_name:application_password --data '{"value": "my_password"}' http://localhost:8095/crowd/rest/usermanagement/1/authentication?username=my_username --header 'Content-Type: application/json' --header 'Accept: application/json' ... { "reason" : "INVALID_USER_AUTHENTICATION", ...
Discussions

Using Json string in the Http Header - Stack Overflow
Sign up to request clarification or add additional context in comments. ... Can you please tell, is it good practice to send json in the header? What is the difference between these two approaches? When to use which? 2017-03-30T01:36:32.787Z+00:00 ... Save this answer. ... Show activity on this post. Base64encode it before sending. Just like how JSON Web Token do it. Here's a NodeJs Example... More on stackoverflow.com
🌐 stackoverflow.com
REST API - Use the "Accept: application/json" HTTP Header - Stack Overflow
When I make a request, I get a response in XML, but what I need is JSON. In the doc it is stated in order to get a JSON in return: Use the Accept: application/json HTTP Header. Where do I find the... More on stackoverflow.com
🌐 stackoverflow.com
How to Use Headers When Reading JSON URL?
Here's a simple example on how to include headers with requests: url = "http://localhost:8080" data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) When you examined the request in the Dev Tools panel, the user: JSON was in the headers section? More on reddit.com
🌐 r/learnpython
2
0
November 7, 2023
VaRest POST example

I can get you an example in 8 or 9 hours when I make it into work, so if no one has given you anything by then, expect it.

More on reddit.com
🌐 r/unrealengine
12
9
January 31, 2018
🌐
Google Cloud
cloud.google.com › cloud storage › http headers and common query string parameters for json
HTTP headers and common query string parameters for JSON | Cloud Storage | Google Cloud Documentation
A request header used in resumable uploads. Query string parameters that can be used in any JSON API request are shown in the table below. Note that not all parameters apply to all requests. For example, use of the fields parameter has no effect on Delete requests, since the response body is empty.
🌐
ReqBin
reqbin.com › req › 5nqtoxbx › get-json-example
How to get JSON from URL?
January 17, 2023 - To request JSON from an URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.
Top answer
1 of 5
44

Yes, you may use JSON in HTTP headers, given some limitations.

According to the HTTP spec, your header field-body may only contain visible ASCII characters, tab, and space.

Since many JSON encoders (e.g. json_encode in PHP) will encode invisible or non-ASCII characters (e.g. "é" becomes "\u00e9"), you often don't need to worry about this.

Check the docs for your particular encoder or test it, though, because JSON strings technically allow most any Unicode character. For example, in JavaScript JSON.stringify() does not escape multibyte Unicode, by default. However, you can easily modify it to do so, e.g.

Copyvar charsToEncode = /[\u007f-\uffff]/g;
function http_header_safe_json(v) {
  return JSON.stringify(v).replace(charsToEncode,
    function(c) {
      return '\\u'+('000'+c.charCodeAt(0).toString(16)).slice(-4);
    }
  );
}

Source

Alternatively, you can do as @rocketspacer suggested and base64-encode the JSON before inserting it into the header field (e.g. how JWT does it). This makes the JSON unreadable (by humans) in the header, but ensures that it will conform to the spec.


Worth noting, the original ARPA spec (RFC 822) has a special description of this exact use case, and the spirit of this echoes in later specs such as RFC 7230:

Certain field-bodies of headers may be interpreted according to an internal syntax that some systems may wish to parse.

Also, RFC 822 and RFC 7230 explicitly give no length constraints:

HTTP does not place a predefined limit on the length of each header field or on the length of the header section as a whole, as described in Section 2.5.

2 of 5
18

Base64encode it before sending. Just like how JSON Web Token do it.
Here's a NodeJs Example:

Copyconst myJsonStr = JSON.stringify(myData);
const headerFriendlyStr = Buffer.from(myJsonStr, 'utf8').toString('base64');
res.addHeader('foo', headerFriendlyStr);

Decode it when you need reading:

Copyconst myBase64Str = req.headers['foo'];
const myJsonStr = Buffer.from(myBase64Str, 'base64').toString('utf8');
const myData = JSON.parse(myJsonStr);
🌐
ReqBin
reqbin.com › req › 4rwevrqh › post-json-example
How do I post JSON to the server?
January 16, 2023 - Additionally, you can pass an "Accept: application/json" header, which tells the server that the client is expecting JSON data. In this POST JSON example, we send JSON data to the ReqBin echo URL with the ...
🌐
ReqBin
reqbin.com › req › gzezk8d5 › json-response-example
How do I return JSON in response?
In this JSON response example, we send a request to the ReqBin echo URL and provide the "Accept: application/json" request header to tell the server that the client is expecting JSON.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › HTTP › Reference › Headers › Content-Type
Content-Type header - HTTP - MDN Web Docs - Mozilla
The following example shows a 201 Created response showing the result of a successful request: http · HTTP/1.1 201 Created Content-Type: application/json { "message": "New user created", "user": { "id": 123, "firstName": "Paul", "lastName": "Klee", "email": "p.klee@example.com" } } Accept, ...
🌐
ReqBin
reqbin.com › req › abghm4zf › json-content-type
What is the correct Content Type for JSON?
January 13, 2023 - The default encoding for JSON (JavaScript Object Notation) is UTF-8. In this JSON Content-Type example, we send JSON to the ReqBin echo URL with an application/json Content-Type header.
Top answer
1 of 5
125

You guessed right, HTTP Headers are not part of the URL.

And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.

The most common scenario is that your server consumes a third party REST Api.

To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).

The code to forge the request, send it and finally get the response back depends on your server side language.

If you want to test a REST Api you may use curl tool from the command line.

curl makes a request and outputs the response to stdout (unless otherwise instructed).

In your case the test request would be issued like this:

$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'

The H or --header directive sets a header and its value.

2 of 5
9

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}
🌐
freeCodeCamp
freecodecamp.org › news › what-is-the-correct-content-type-for-json-request-header-mime-type-explained
What is the Correct Content-Type for JSON? Request Header Mime Type Explained
December 8, 2020 - The media type of any resource is declared in the Content-Type property of the request header (on the client, when making a request to the server) or in the response header (on the server, when sending a response). Without explicitly declaring the content type of a resource, the client may attempt to automatically detect the type, but the result may not be accurate. This is why it's important to explicitly declare it. Media types exist in various forms. They are categorized into various groups: ... These categories also have their types. For example, application/json is a type under application and text/html is a type under text.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Fetch_API › Using_Fetch
Using the Fetch API - Web APIs | MDN
For example, we can make a POST ... myHeaders.append("Content-Type", "application/json"); const response = await fetch("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), headers: myHeaders, });...
🌐
Reddit
reddit.com › r/learnpython › how to use headers when reading json url?
r/learnpython on Reddit: How to Use Headers When Reading JSON URL?
November 7, 2023 -

Hi all! Thanks in advance for any guidance. I'm trying to read a JSON url in Python. When I open the url in chrome, I can see the data, but when I read it in python, I get {'error': 'Unauthorized'}. When I open the url in Edge, I get the same error. I determined it was because I have to be logged in to the website through my gmail account, and then I can see the JSON data. When I inspect the site's Network, I see a request called Session that contains the following (I changed some of the personal details):

{
"user": {
    "email": "ekraft@gmail.com",
    "sub": "58edee6c-e210-4f2c-99a2-568efde67a6a",
    "auth0_id": "google-oauth2|106222607358455934444",
    "username": "ekraft"
    }
    "expires": "2023-12-07T20:21:51.686Z"
}

Below is my current script. I googled more on it and it seems I have to work with these headers, but I'm not quite sure how to implement them. Any guidance is greatly appreciated!

import requests
url = "https://www.otmnft.com/api/reignmakerspro/football/liveListings"
response = requests.get(url) 
print(response.json())

🌐
Baeldung
baeldung.com › home › web › sending json http request body in terminal
Sending JSON HTTP Request Body in Terminal | Baeldung on Linux
March 18, 2024 - In this tutorial, we’ll be learning how to send JSON objects as the request body correctly with the help of the Content-Type HTTP header. In Linux, curl and wget are the common terminal-based HTTP clients. Given its popularity in the Linux ecosystem, we’ll be using them in this article for demonstration purposes. To obtain curl and wget, we can install them using the package manager. For example, in Ubuntu Linux, we can run apt-get install to obtain these programs:
🌐
Stimulsoft
stimulsoft.com › en › blog › articles › http-headers-in-json-data
HTTP headers in JSON data sources
May 16, 2024 - This is relevant in cases where JSON data is obtained from a URL using the HTTP or HTTPS protocol. Accordingly, if the URL begins with http:// or https://, then the data will be loaded through the WebClient. In this scenario, it is possible to configure request HTTP headers in the form of a Key-Value pair in the data source editor.
🌐
Progress
documentation.progress.com › output › Corticon › 5.6.1 › html › corticon › sample-json-request-and-response-messages.html
Sample JSON request and response messages
When both major and minor version are provided, that version of the Decision Service handles the request. content-type:application/json dsName:ProcessOrder dsEffectiveTimestamp:12/11/2015 ...
🌐
Informatica
docs.informatica.com › reference material › rest api reference › informatica intelligent cloud services rest api › header and body configuration › json format example
JSON format example
You can then use the sessionId and the baseapiUrl to construct a request to obtain your organization's license information, for example: GET https://https://usw3.dm-us.informaticacloud.com/saas/public/core/v3/license/org/52ZSTB0IDK6dXxaEQLUaQu Content-Type: application/json Accept: application/json INFA-SESSION-ID: 9KA11tLGqxVcGeul8SQBK3 · Header and body configuration ·