vendredi 24 juin 2016

What should I put in the body of the response for this POST request?

I'm trying to make a REST API that uses a POST to create a new object in my database. I'm using the Slim framework.

The problem it's that I'm not sure about what I exactly have to put in these lines on my POST method:

$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode(**Here they put the name of the type of the object that they have in their database**));

My full POST route is:

$app->post("/cars/", function() use($app)
{
    $idCar = $app->request->post("idCar");
    $name = $app->request->post("name");

    try{
        $connection = getConnection();
        $dbh = $connection->prepare("INSERT INTO cars VALUES(?,?)");
        $dbh->bindParam(1,$idCar);
        $dbh->bindParam(2,$name);

        $dbh->execute();
        $connection = null;

        $app->response->headers->set("Content-type","application/json");
        $app->response->status(200);
        $app->response->body(json_encode(**What I have to put here?**));

    }catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }
});

In the table cars there are objects Car.

Should I put it like this?:

$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($Car));

I'm a bit confused because in the tutorials that I saw before, in the POST method they don't have any reference to the name of the variable inside the POST route. For example, if they use $fruit they didn't declare any variable named $fruit inside their route.

What should I do? Is my answer correct?

Aucun commentaire:

Enregistrer un commentaire