Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build optional parameters as question marks in Slim?

Tags:

rest

php

api

slim

I've built my first RESTful API ever and used Slim as my framework. It works well so far.

Now I have seen a great API Design Guide which explained, the best way to build an API is to keep the levels flat. I want to do that and try to figure out how to build an URI like this:

my-domain.int/groups/search?q=my_query

The /groups part already works with GET, POST, PUT, DELETE and also the search query works like this:

my-domain.int/groups/search/my_query

This is the code I use for the routing in PHP:

$app->get('/groups/search/:query', 'findByName');

I just can't figure out how to build optional parameters with an question mark in Slim. I wasn't able to find anything on Google.

EDIT: Since the search not seems to be suitable for my scenario I try to show another way of what I want to realize:

Let's say I want to get a partial response from the API. The request should look like that:

my-domain.int/groups?fields=name,description

Not like that:

my-domain.int/groups/fields/name/description

How do I realize that in the routing?

like image 268
Raphael Avatar asked Jun 16 '14 10:06

Raphael


1 Answers

The parameters supplied with the query string, the GET parameters, don't have to be specified in the route parameter. The framework will try to match the URI without those values. To access the GET parameters you can use the standard php approach, which is using the superglobal $_GET:

$app->get('/groups/test/', function() use ($app) {
    if (isset($_GET['fields']){
        $test = $_GET('fields');
        echo "This is a GET route with $test";
    }
});

Or you can use the framework's approach, as @Raphael mentioned in his answer:

$app->get('/groups/test/', function() use ($app) {
    $test = $app->request()->get('fields');
    echo "This is a GET route with $test";
});
like image 193
TPete Avatar answered Sep 20 '22 22:09

TPete