1

I am testing a API using CURL in my local server. I need to use CURL GET request with a Json parameters.

My Json will be like: { "key1" :[{subkey1":"subvalue1","subkey2":"subvalue2"}], "key2" :[{subkey3":"subvalue3","subkey4":"subvalue4"}]} And I tried: curl -i http://localhost/test/api?key1

or save my json file as a test.txt and use curl -X POST -H 'Content-type:application/json' --data-binary '@D:/test.txt' http://localhost/test/api?key1

.....but none of them work.... So how could I use a curl to create a post request with payload? Thanks!

I want to get the return value as key1 = [ ***] key2 = [####]

2
  • At first you said you were trying to make a GET request and then later a POST request - which once does the server actually accept? Commented Mar 30, 2023 at 14:36
  • oh, sorry, it should be a post request...not GET Commented Mar 30, 2023 at 15:38

1 Answer 1

1

There are many different ways to send JSON with curl. Consult your API documentation to check which method you should use.

Here are some common ones:

sending json in a application/x-www-form-urlencoded POST request can be done like:

curl http://example.com --data-urlencode json='{"foo":"bar"}'

the request will then look like:

POST / HTTP/1.1
Host: example.com
User-Agent: curl/7.87.0
Accept: */*
Content-Length: 32
Content-Type: application/x-www-form-urlencoded

json=%7B%22foo%22%3A%22bar%22%7D

json in a multipart/form-data POST request can be done like:

curl http://example.com --form json='{"foo":"bar"}'

the request will then look like

POST / HTTP/1.1
Host: example.com
User-Agent: curl/7.87.0
Accept: */*
Content-Length: 152
Content-Type: multipart/form-data; boundary=------------------------ca36a58e4d11c82e

--------------------------ca36a58e4d11c82e
Content-Disposition: form-data; name="json"

{"foo":"bar"}
--------------------------ca36a58e4d11c82e--

sending raw json in a POST request can be done like:

curl --header 'Content-Type: application/json' --request POST --data-binary '{"foo":"bar"}'

the request will then look like

POST / HTTP/1.1
Host: example.com
User-Agent: curl/7.87.0
Accept: */*
Content-Type: application/json
Content-Length: 13

{"foo":"bar"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.