I try to make a RESTful api using slim framework.
I do not know details about the slim framework, because i'm beginner of this framework.
So, I followed all steps of how to get data in slimframework. But i can't get POST data.
Follow is my code to get POST data.
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
$app->post('/registration/user', function (Request $request, Response $response) use ($app) {
$data = $request->getParsedBody();
$name = $_POST['name'];
echo '1 : '.$data['name'];
echo '2 : '.$name;
});
That is result of when i send name data.
what i have to do for get post data??
Do you have any idea?
I use \Slim\Http\Request $request->getParsedBody() in my routes. The method contains all the $_POST data.
Example:
$postArr = $request->getParsedBody();
$name = $postArr["name"];
The following can be used:
$body= file_get_contents("php://input");
// $body = $request->getBody();
$data = json_decode($body, true);
Related
I have been using the HTTP client in Laravel 8, as follows:
$http = Http::asForm()->post($url, $post_data);
$response = $http->body();
This works great. Now I want to include a file upload as part of this request, but the file is optional. I have tried to structure my request like this:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
public function index(Request $request)
{
$url = 'my-url';
$post_data = $request->post();
$http = Http::asForm();
if ($request->hasFile('image')) {
$http->attach('image', $request->file('image'));
}
$http->post($url, $post_data);
$response = $http->body();
}
But this is not working. The error I am getting is: Method Illuminate\Http\Client\PendingRequest::body does not exist.
The post() method appears to be returning Illuminate\Http\Client\PendingRequest instead of Illuminate\Http\Client\Response.
Any ideas how to do this?
$response = $http->post($url, $post_data)->body();
// alternatively:
$pendingRequest = $http->post($url, $post_data);
$response = $pendingRequest->body();
In your second code sample, you don't assign the return of post() to a variable. But this return value (Illuminate\Http\Client\PendingRequest) is the object that defines the body() method. So either use a second variable (or reassign $http), or chain the post() and body() calls as shown above.
I'm developing a web RESTful API using slim framework of php.I want to know how do I add some annotation type thing on POST method so that it can behave as URL encoded method.Please help me in this regard.Advance thanks.
There is no pre-programmed way for this - there is no Slim or php method that will definitively check if your string is urlencoded. What you can do is implement Slim Middleware to your route.
<?php
$app = new \Slim\App();
$mw = function ($request, $response, $next) {
if ( urlencode(urldecode($data)) === $data){
$response = $next($request, $response);
} else {
$response = ... // throw error
}
return $response;
};
$app->get('/', function ($request, $response, $args) { // Your route
$response->getBody()->write(' Hello ');
return $response;
})->add($mw); // chained middleware
$app->run();
Discussion: Test if string is URL encoded in PHP
Middleware: https://www.slimframework.com/docs/v3/concepts/middleware.html
Since you're using Slim as the foundation to your API, the easiest way is to just build a GET route with the desired URL parameters defined:
$app->get('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
// Route actions here
});
In your documentation, make sure you inform the consumers of this API that it is a GET endpoint, so that a POST body should not be made; rather, the parameters that you outline in the URL should be used to pass the client's data over to the API.
If you are intent on using a POST route with just URL parameters, then you could also force a response back if the route detects an incoming POST body:
$app->post('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
$postBody = $request->getParsedBody();
if (is_array($postBody)) {
$denyMsg = "This endpoint does not accept POST body as a means to transmit data; please refer to the API documentation for proper usage.";
$denyResponse = $response->withJson($denyMsg, $status = null, $encodingOptions = 0);
return $profileData;
}
});
in vanilla php i would create a callbak url with just
try
{
//response content type application/json
header("Content-Type:application/json");
//read incoming request
$postData = file_get_contents('php://input');
.......
......
but in laravel i'm yet to get a clear explanation on how to achieve the same
ive tried using
$postData = Request::getContent();
but it returns blank
If you need data in request use (new \Illuminate\Http\Request())->all() or use DI
public function someAction(\Illuminate\Http\Request $request)
{
dd($request->all());
}
I'm trying to make a postrequest in slim, my intention is inserting data into a mysql database. It's the first time I try to do this, so sorry if I don't explain myself well.
Here's what I have:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
require "classes/Autoloader.php";
$app = new \Slim\App;
$app->post('/', function(Request $request, Response $response) use ($app) {
$postVars = $request->getParsedBody();
$id = $request->getAttribute('id');
$steps = $request->getAttribute('steps');
$date = $request->getAttribute('date');
echo $id . $steps . $date;
require_once "classes/Connection.php";
$userdata = new Insert($dbh, $id, $steps, $date);
$userdata->insert();
});
$app->run();
My intention is getting the values, and using them to insert the data, but I keep getting Slim's "Page Not Found" error. This is the url I'm trying with: http://localhost/wp-api/?id=1&steps=12&date=8787.
What am I doing wrong, or is this the correct way to do it?
Thanks in advance!
Edit: Following Justal's answer, I changed my code, on line 10; $app->post('/'... specifically. I now get Method not allowed. Must be one of: POST
Edit2: I changed line 12 (getQueryParams -> getParsedBody) , and used Postman, otherwise broswer does a getrequest (source of the previous error). It now inserts null values into the database, though.
page not found because you are requesting get on a post route.try below code.
All Data pass in the $request object.
$app->post('/', function(Request $request, Response $response) {
echo "<pre>";
print_r($request);
exit;
});
The function is simple, I need to forward a post request to an external API service. I am using Laravel 5.5 and the $client is Guzzle 6 client;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
public function insert(Request $request)
{
try {
$body = $request->json()->all();
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);
return response($response->getBody(),$response->getStatusCode())>withHeaders($response->getHeaders());
}catch(Exception $e){
.....
}
}
the problem is the $bodyStringRAW = $request->json()->all();
the data send to laravel is
[{"name":"Secion4小明","comment":"","applicationId":"59"}]
the data received by the external API is [{"name":"Secion4\u5c0f\u660e","comment":null,"applicationId":"59"}]
If i change the code to
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$request->getContent()]);
the external API received the data as
[{\"name\":\"Secion4\u5c0f\u660e\",\"comment\":\"\",\"applicationId\":\"59\"}]
How can I make the encoding correct? I Can't find the way to set the encoding.
Update 1:
$body = utf8_decode($request->getContent());
$response = $this->client->post($this->generateUrl("/api/sections?", $request->getQueryString()), ['json' =>$body]);
External API got
[{\"name\":\"Secion4??\",\"comment\":\"\",\"applicationId\":\"59\"}]
The data is is Unicode, you can convert with utf8_decode.