Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get JSON POST data submitted via Slim

Tags:

post

php

slim

Im using Postman (in Chrome) to test Slim calls but cant figure out how to get any of the posted JSON data.

Im submitting raw JSON:

{"name":"John Smith", "age":"30", "gender":"male"}

With Content-Type: application/json in the header

via POST to:

http://domain/api/v1/users/post/test/

Every attempt to get the JSON data gives a fatal error (see code comments below)

<?php
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\ContentTypes());


$app->group('/api/v1', function () use ($app) {

    $app->group('/users/post', function () use ($app) {

        $app->post('/test/', function () {

                print_r($app->request->headers); //no errors, but no output?

                echo "Hello!"; // outputs just fine

        $data = $app->request()->params('name'); //Fatal error: Call to a member function request() on a non-object
                $data = $app->request->getBody(); //Fatal error: Call to a member function getBody() on a non-object
                $data = $app->request->post('name'); //Fatal error: Call to a member function post() on a non-object
                $data = $app->request()->post(); //Fatal error: Call to a member function request() on a non-object

                print_r($data);
                echo $data;

        });

    });

});

$app->run();
?>

What am I missing?

Thanks!

like image 478
Ahhk Avatar asked Dec 02 '13 03:12

Ahhk


3 Answers

Make sure to curry $app into the last nested route, like so:

// Pass through $app
$app->post('/test/', function () use ($app) {

You're doing it everywhere else, so I'm assuming you just overlooked it.

like image 183
Jeremy Kendall Avatar answered Nov 18 '22 08:11

Jeremy Kendall


you have to get the body from the request:

$app->request->getBody();

http://docs.slimframework.com/request/body/

like image 1
Antonio Romero Oca Avatar answered Nov 18 '22 08:11

Antonio Romero Oca


In Slim 3 I've used the value of body in curl POST data and it didn't work, to fix this I've used this, the body is object not string:

$app->post('/proxy', function($request, $response) {
    $data = $request->getBody()->getContents();
    $response->getBody()->write(post('http://example.com', $data));
});

You can check more methods on body in docs

like image 1
jcubic Avatar answered Nov 18 '22 07:11

jcubic