How do I return JSON in HTTP response? [Curl/Bash Code]
To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly. 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. In response to our request, the server sends us a JSON response and includes the "Content-Type: application/json" and Content-Length headers, which indicate the type and size of the data in the response body. Click Send to execute return JSON in the web HTTP response, and see the results. The Curl/Bash code was automatically generated for the JSON Response example.
Hypertext Transfer Protocol is a data transfer protocol between two computers that are used to transfer data between an HTTP client (browser or mobile application) and a server. HTTP is built around messages called "request" and "response". Devices communicate with each other by sending HTTP requests and receiving HTTP responses. All modern programming languages natively support HTTP.
What it JSON?
How to send data in JSON format?
You can send JSON data to the server in the body of an HTTP request or return JSON data from the server in the body of an HTTP response. In both cases, you must explicitly specify the type of data in the body of the HTTP message using the Content-Type: application/json header (the application/json is the official MIME Type for JSON). The correct Content-Type header allows the server to interpret the data in the client's request correctly and will enable clients to correctly interpret the data in the server's response. Providing the Content-Length header is optional. If you don't know the size of JSON data, you may use chunked transfer encoding for your response.
JSON Response Example
An example of JSON response when fetching data from ReqBin echo URL:
JSON Response Example
HTTP/1.1 200 OK