I turned in my api recently. All requests on one page, but my teacher wanted me to split them into multiple pages so it is more managable. Now I run in to some trouble, because only one of the pages is working. The method I am trying now is as follows.
This is my allcountry.php file which is working just fine
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Spatie\ArrayToXml\ArrayToXml;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/config/db.php';
$app = new \Slim\App;
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
$app->get('/api/country', function (Request $request, Response $response) {
$sql = "SELECT * FROM country";
try {
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->execute();
$worlds = $stmt->fetchAll(PDO::FETCH_OBJ);
$stmt1 = $db->prepare($sql);
$stmt1->execute();
$worldsxml = $stmt1->fetchAll(PDO::FETCH_ASSOC);
$db = null;
// JSON validator and schema
$data = (object) $worlds;
// Convert data to XML format
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><world></world>');
foreach ($worldsxml as $world) {
$node = $xml->addChild('country');
foreach ($world as $key => $value) {
$node->addChild($key, $value);
}
}
$acceptHeader = $request->getHeaderLine('Accept');
if ($acceptHeader == 'application/xml') {
// Check if XML is valid
$xmlString = $xml->asXML();
$xsdString = file_get_contents(__DIR__ . '/xsdcountry.xsd');
$dom = new DOMDocument();
$dom->loadXML($xmlString);
if ($dom->schemaValidateSource($xsdString)) {
$response = $response->withHeader('Content-Type', 'application/xml');
$response->getBody()->write($xmlString);
} else {
// Invalid XML
$response = $response->withStatus(400);
$response->getBody()->write('Invalid XML');
}
} else {
// Load the schema from the file
$schema = json_decode(file_get_contents(__DIR__ . '/Json.json'), false);
// Now you can use the $schema variable as before
$validator = new League\JsonGuard\Validator($data, $schema);
if ($validator->passes()){
$response = $response->withHeader('Content-Type', 'application/json');
$response->getBody()->write(json_encode($worlds));
}
else {
echo json_encode($validator->errors());
}
}
return $response;
} catch (PDOException $e) {
$response = $response->withStatus(500);
$response->getBody()->write(json_encode(['error' => ['text' => $e->getMessage()]]));
return $response;
}
});
$app->run();
?>
This is my allcity.php which gives me an error:
Method not allowed
Method not allowed. Must be one of: OPTIONS
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Spatie\ArrayToXml\ArrayToXml;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/config/db.php';
$app = new \Slim\App;
$app->options('/{routes:.+}', function ($request, $response, $args) {
$allowedMethods = $request->getHeaderLine('Access-Control-Request-Method');
$response = $response->withHeader('Access-Control-Allow-Methods', $allowedMethods);
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
// Get All City
$app->get('/api/city' , function(Request $request, Response $response){
$sql = "SELECT * FROM city";
try{
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$stmt1 = $db->query($sql);
$worlds = $stmt->fetchAll(PDO::FETCH_OBJ);
$worldsxml = $stmt1->fetchAll(PDO::FETCH_ASSOC);
$db = null;
//put data in object
$data = (object)$worlds;
// Convert data to XML format
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><world></world>');
foreach ($worldsxml as $world) {
$node = $xml->addChild('city');
foreach ($world as $key => $value) {
$node->addChild($key, $value);
}
}
$acceptHeader = $request->getHeaderLine('Accept');
if ($acceptHeader == 'application/xml') {
// Check if XML is valid
$xmlString = $xml->asXML();
$xsdString = file_get_contents(__DIR__ . '/xsdcity.xsd');
$dom = new DOMDocument();
$dom->loadXML($xmlString);
if ($dom->schemaValidateSource($xsdString)) {
$response = $response->withHeader('Content-Type', 'application/xml');
$response->getBody()->write($xmlString);
} else {
// Invalid XML
$response = $response->withStatus(400);
$response->getBody()->write('Invalid XML');
}
} else {
// Load the schema from the file
$schema = json_decode(file_get_contents(__DIR__ . '/Json.json'), false);
// Now you can use the $schema variable as before
$validator = new League\JsonGuard\Validator($data, $schema);
if ($validator->passes()){
$response = $response->withHeader('Content-Type', 'application/json');
$response->getBody()->write(json_encode($worlds));
}
else {
echo json_encode($validator->errors());
}
}
return $response;
} catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
});
$app->run();
?>
This is my .htacces file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . allCountry.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . allCity.php [L]
If I remove the allcountry.php part, the api/city works.
Is there someone who could help me out?