Skip to content

API Middleware #65

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Middleware/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php
/**
* API Middleware Class for the Slim Framework
*
* @author Montana Flynn <[email protected]>
* @since 3/10/13
*
* Simple class to make building API's easier
*
* Usage
* ====
*
* $api = new \Slim\slim();
* $api->add(new \Slim\Extras\Middleware\API());
*
*/

namespace Slim\Extras\Middleware;

class API extends \Slim\Middleware
{
public function call()
{

// Just to make things easy, we can avoid the 404 page and override with
// helpful error messages. May extend later to find all registered endpoints
$app = $this->app;

// Change to json
$response = $app->response();
$response['Content-Type'] = 'application/json';

// No Endpoint Specified?
$app->get('/', function() use ($app) {
$app->halt(400, json_encode(array('error'=>'You must specify an endpoint!')));
});

// Cannot Find Endpoint?
$app->get('/:method', function($method) use ($app) {
$app->halt(400, json_encode(array('error'=>'There is no endpoint named '.$method.'!')));
})->conditions(array('method' => '.+'));

// Move along to next call
$this->next->call();

// But wait! Let's add support for jsonp callbacks
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The middleware class with the same functionality already exists here: Middleware/Jsonp.php

$request = $app->request();
$callback = $request->params('callback');

if(!empty($callback)){
$app->contentType('application/javascript');
$jsonp_response = $callback . "(" .$app->response()->body() . ")";
$app->response()->body($jsonp_response);
}
}
}