Return http 500 with Slim framework - php

If somethings goes bad in my API i want to return a http 500 request.
$app = new Slim();
$app->halt(500);
It still return a http 200.
If i run this code:
$status = $app->response()->status();
echo $status; //Here it is 200
$status = $app->response()->status(500);
echo $status; //Here it is 500
it stills give me a http 200

The $app->response()->status(500); is correct, see the docs here.
Check to make sure you're calling $app->run(); after setting the status, this will prepare and output the response code, headers and body.
Edit, make sure you define a route or Slim will output the 404 response, this works:
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->response()->status(500);
$app->get('/', function () {
// index route
});
$app->run();

If anyone still has this issue here is what I ended up doing:
Setup an error handler
$app->error(function (Exception $exc) use ($app) {
// custom exception codes used for HTTP status
if ($exc->getCode() !== 0) {
$app->response->setStatus($exc->getCode());
}
$app->response->headers->set('Content-Type', 'application/json');
echo json_encode(["error" => $exc->getMessage()]);
});
then, anytime you need to return a particular HTTP status throw an Exception with the status code included:
throw new Exception("My custom exception with status code of my choice", 401);
(Found it on the Slim forum)

If you have to push header after $app->run(), you can always rely on the header php function:
header('HTTP/1.1 401 Anonymous not allowed');

Slim framework v2 wiki status
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/', function () use ($app) {
$app->response()->setStatus(500);
$app->response()->setBody("responseText");
return $app->response();
});
$app->run();
or
$app->get('/', function () use ($app) {
$app->halt(500, "responseText");
});

Related

How to use guzzle to simulate event loop HTTP pool

test.php
<?php
//simulate different blocking times
if(isset($_GET['appid'])) {
sleep(rand(3, 10));
echo $_GET['appid'];
exit;
}
client.php
<?php
require './vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;
$client = new Client();
$promise = null;
$loop = function ($appId) use($client, &$loop, &$promise) {
$promise = $client->getAsync("http://127.0.0.1/test.php?appid={$appId}");
$promise->then(
function (ResponseInterface $res) use(&$loop, $appId) {
echo $res->getBody();
//After completing the current request, initiate the request again to simulate EventLoop
$loop($appId);
},
function (RequestException $e) use(&$loop, $appId) {
//Ignore the error and continue to simulate EventLoop
$loop($appId);
}
);
};
foreach(range(1, 10) as $appId) {
$loop($appId);
}
$promise->wait();
I try to use promise to simulate EventLoop. As shown in my example code, I have 10 application IDs. I want to launch 10 requests concurrently. At the same time, the response time of each request is different. I want to launch the request of the current application ID immediately after each request is completed to simulate EventLoop.
But I find it doesn't seem to work. How can I simulate EventLoop

Renamed index.php then Slim API stopped working

I had my slim API working, but then i decided to rename my index.php. After renaming it, it wouldn't work. So I renamed it back to index.php and deleted the other index.php. However, now it won't work at all.
My index looks as follows:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require './vendor/autoload.php';
require './config/db.php';
//authenticator
// routes
require './routes/product.php';
require './routes/login.php';
require './routes/cart.php';
require './routes/wishlist.php';
// run app
$app->run();
My product route looks as follows:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
// all entries
$app->get('/api/products/all', function (Request $request, Response $response) {
$sql = "SELECT * FROM product_endpoint";
try
{
$db = new DB();
$conn = $db->connect();
$stmt = $conn->query($sql);
$product = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
$response->getBody()->write(json_encode($product));
return $response
->withHeader('content-type', 'application/json')
->withStatus(200);
} catch (PDOException $e)
{
$error = ["message" => $e->getMessage()];
$response->getBody()->write(json_encode($error));
return $response
->withHeader('content-type', 'application/json')
->withStatus(500);
}
});
Before I renamed my index.php this worked perfectly, however now I'm just greeted with "page not found" when i navigate to my api endpoint.
index.php is located at root and the route is located in a file called "route".
Can anyone kindly assist? Thank you.

Doing a post request via url in Slim Framework

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;
});

Ping using Guzzle Http php

I want to use guzzle http for ping.
I dont care about the response.
Just request is enough.
No need of response.
After request the code need to exits. Dont wait for response.
I tried to do with async.
<?php
require_once "vendor/autoload.php";
$client = new GuzzleHttp\Client();
$promise1 = $client->requestAsync('GET', 'http://localhost/test/?id=from_async1');
$promise2 = $client->requestAsync('GET', 'http://localhost/test/?id=from_async2');
$promise3 = $client->requestAsync('GET', 'http://localhost/test/?id=from_async3');
$promise1->then(function (ResponseInterface $response) {
});
$promise2->then(function (ResponseInterface $response) {
});
$promise3->then(function (ResponseInterface $response) {
});
$promise1->wait();
$promise2->wait();
$promise3->wait();
But still this script waits for all response to come back.
How to get the script work without waiting for response? Any thoughts?

Setting up the Slim framework

I'm following the tutorial on: http://www.slimframework.com/docs/tutorial/first-app.html
And it's telling me to add the following code to my index.php file:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
$app->run();
However when I use Postman to do an API call to my server running the php program above I get the following response:

Categories