0

I want to send ['1', '2', '3'] as a GET request. I thought GET request are used when you are retrieving data opposed to POST (when you are modifying/creating data)

Failing to google how to send list of strings with GET does make me wonder, if it's better to use POST here?

eugene
  • 39,839
  • 68
  • 255
  • 489
  • 1
    How do you intend to send it? In the query string? In the payload? – cassiomolin Apr 12 '19 at 10:03
  • Oh I thought GET uses query string, (appended at the end of url), Is there other way of sending data other than query string when using GET? – eugene Apr 12 '19 at 10:08
  • You could also put extra data in the request headers, but if they're intended to change the result of the GET then that feels wrong. – Rup Apr 12 '19 at 10:12
  • What do the 1,2,3 represent? If it's e.g. a search query, i.e. getting 1,2,3 again should return (more or less) the same results, then GET probably does make sense. If it's intended to change things then you should probably use something else. Why do you want to use GET? – Rup Apr 12 '19 at 10:12

2 Answers2

3

Once you intend to perform a GET request, you could send data in the query string using one of the following approaches:

curl -G http://example.org -d "query=1,2,3"
curl -G http://example.org -d "query=1&query=2&query=3"

Let me highlight that payloads in GET requests are not recommended. Quoting the RFC 7231:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

Also bear in mind that GET requests shouldn't be used to modify resources: they are intended to be used for information retrieval only, without side effects. Having said that, GET is both safe and idempotent. You can see more details on these concepts in this answer.


If the data must be sent in the payload (and you intend to modify the resource) then stick to POST. Assuming your payload is a JSON document, you would have something like:

curl -X POST http://example.org \
-H "Content-Type: application/json" \
-d '["1", "2", "3"]'
Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 1
    actually using `"query=1,2,3"` , I got "1,2,3" from the receiving end point, (need manual parsing), well I guess it depends on what libraries you are using on the receiving end point.. – eugene Apr 12 '19 at 11:25
0

If you want to send it in the body with curl you can call your service like this:

curl -X GET --data "['1', '2', '3']" "https://example.com/test.php"

For example in PHP you can read it from the read-only stream php://input

<?php
$get_body = file_get_contents('php://input');

A better way would be to assign the array to a parameter e.g. x:

curl -X GET "https://example.com/test.php?x[]=1&x[]=2&x[]=3"

In PHP you'll receive these values as an array in $_GET['x']:

<?php
print_r($_GET['x']);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Markus D.
  • 294
  • 3
  • 5