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.
Related
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;
});
i have uploaded my laravel project to live server but its not working when i track code i get the execption that class request does not exists,please help me to find out the error
this is my file
index.php
<?php
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$app->bind('path.public', function() {
return __DIR__;
});
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
try{
$request = App\Http\Request::capture()
}
catch(Exception $e)
{
echo "error:".$e->getMessage()."<br>";
}
$response = $kernel->handle(
$request = App\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
Request facade usually lives in a different namespace. Try replacing any reference to
App\Http\Request
with just
Request
in order to access the facade by its global namespace alias.
I have this code:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
require '../src/config/db.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Let's get started, $name");
return $response;
});
// Customer Routes
require '../src/routes/customers.php';
// Calendar Routes
require '../src/routes/calendar.php';
$app->run();
The require '../vendor/autoload.php'; is for Composer.
The browser only displays the last require statement, which is in this case:
// Calendar Routes
require '../src/routes/calendar.php';
If I want to display, for example, customers.php, then I would need to change the require order like this:
// Calendar Routes
require '../src/routes/calendar.php';
// Customer Routes
require '../src/routes/customers.php';
I would like to be able to display both require statemnts and $app->get('/hello/{name}' at once, with just typing different http://localhost in the browser.
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:
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");
});