Search code examples
ajaxhttphttp-gethttp-request-parameters

Can I pass an object as one of the parameters when I do the get request?


I have an parameter values like this:

user = {id: 1, name="tester", age="23"}

Can I pass the entire object as one of parameters in HTTP.GET request? If yes, how can I test it in my postman?


Solution

  • You can use different ways - PHP's serialize function:

    $user = array(
        "id" => 1,
        "name" => "tester",
        "age" => 23
    );
    
    echo serialize($user);
    echo '</br>';
    echo var_dump(unserialize($_GET['user']));
    

    Which results in the call URL:

    ?user=a:3:{s:2:%22id%22;i:1;s:4:%22name%22;s:6:%22tester%22;s:3:%22age%22;i:23;}
    

    Or you could simply json_encode the object:

    $user = array(
        "id" => 1,
        "name" => "tester",
        "age" => 23
    );
    
    echo json_encode($user);
    echo '</br>';
    var_dump(json_decode($_GET['user']));
    

    Which results in the call URL:

    ?user={"id":1,"name":"tester","age":23}
    

    This will work as long as the parameters in the URL are safe. If you can't be sure that it will be the case, you can urlencode the parameter:

    $user = array(
        "id" => 1,
        "name" => "tester",
        "age" => 23
    );
    
    echo urlencode(json_encode($user));
    echo '</br>';
    var_dump(json_decode(urldecode($_GET['user'])));
    

    Which will result in the encoded URL:

    ?user=%7B%22id%22%3A1%2C%22name%22%3A%22tester%22%2C%22age%22%3A23%7D
    

    PHP was only used as an example here - but json and urlencoding is available in almost every language used nowadays.