GoldenJoe
GoldenJoe

Reputation: 8002

Which Is Better Using POST Arguments Or JSON in REST API?

In previous projects I worked on, our API would take and validate each POST argument individually by value:

$username   = isset($_POST['username']) ? $_POST["username"] : null;
$password   = isset($_POST['password']) ? $_POST["password"] : null;

Multidimensional arrays can be a bit tricky this way, though.

For a new project, I am consider a more object-oriented approach, and taking the JSON needed to construct objects instead of each individual field:

$user       = isset($_POST['user'])     ? new User($_POST['user']) : null;

Which practice is more common, and why? Are there extra security risks using one or the other?

Upvotes: 3

Views: 2570

Answers (2)

Dolly Aswin
Dolly Aswin

Reputation: 2794

For developing REST API, I prefer to use JSON as Request (than POST arguments) and Response.

For Client side, making json request is not difficult. All language has support JSON now.

And for Server side (PHP), retrieving JSON in body request is not difficult too.

// $data will be array of data
$data = json_decode(file_get_contents('php://input'), true);

And using JSON for both Request and Response, will make API Documentation easy to read.

And for security section, AFAIK there is no problem using JSON in body request,

Upvotes: 2

Jim Wright
Jim Wright

Reputation: 6058

There aren't any security advantages over either. If someone intercepts the request then they will be able to see the POST data whether it is in different arguments or just the body.

Make sure that you are using SSL to prevent prying eyes.

As far as JSON body vs POST arguments, it really depends on how you will be using the API. Are you going to use a front-end JS framework or jQuery? Then JSON will probably be easier for you. Does your API return JSON? Then it should probably accept JSON too.

Remember that you could always handle different content types based on the Content-Type header!

Upvotes: 3

Related Questions