Mark Rune
Mark Rune

Reputation: 37

Routes - Slimframework

I am trying to make a simple API that will print cars for me. So far I made a 3 simple routes:

$app('/api/cars', function($req, $res, $arg) {
    //Display all cars
});
$app('/api/cars/{brand}', function($req, $res, $arg) {
    //Display all cars based on brand
});
$app('/api/cars/{brand}/{model}', function($req, $res, $arg) {
    //Display all cars based on brand
});

And it works just fine. But what if I want to display cars with "?" color? let's say: api/cars/red I am unable to.

I can't really do that, because it's looking for a brand name instead of a color.

Upvotes: 2

Views: 43

Answers (2)

Joseph Cho
Joseph Cho

Reputation: 4214

Based on your route you wouldn't be able to, because as you've pointed out it's looking for a brand. If you want a quick and dirty solution you could update your endpoints to be slightly more descriptive.

For example:

$app('/api/cars/brand/{brand}', function($req, $res, $arg) {
    //Display all cars based on brand
});
$app('/api/cars/color/{color}', function($req, $res, $arg) {
    //Display all cars based on color
});

This reduces any ambiguity on what the endpoint should expect. Ideally your API should accept query strings instead.

Upvotes: 0

Alex Howansky
Alex Howansky

Reputation: 53636

You could pass the additional filters as GET parameters on the URL:

/api/cars?color=red

/api/cars/honda?color=red

/api/cars/honda/civic?color=red

Then you can use $request->getParam('color') to read it.

Upvotes: 2

Related Questions