LB_Donegal
LB_Donegal

Reputation: 1

How do I exclude a query variable from a HTTP GET request if the user hasn't inputted a value?

I am sending a GET request to an external API that works fine if a user enters a value into all applicable fields. I'd like to have all of these fields optional, except of course the first one to ensure we get a response.

Is there a simple method I can use that will ignore these from the request?

These are the variables I'll be passing into the request

$query = $request->input('query');
    $include = $request->input('include');
    $include2 = $request->input('include2');
    $include3 = $request->input('include3');
    $exclude = $request->input('exclude');
    $exclude2 = $request->input('exclude2');

This is the request which may look confusing as a whole but its pretty simple. The user can enter in a base ingredient as a query and further refine their recipe search by entering specific ingredients to include or exclude. I'd like to know how to pass this request if for example the user only entered two included ingredients and one excluded ingredient

$res = $client->get('http://api.yummly.com/v1/api/recipes?_app_id='MY_ID'&_app_key='MY_KEY'&q='.$query.'&allowedIngredient[]='.$include.'&allowedIngredient[]='.$include2.'&allowedIngredient[]='.$include3.'&excludedIngredient[]='.$exclude.'&excludedIngredient[]='.$exclude2.'&maxResult=50', ['auth' =>  ['user', 'pass']]);
        $body = json_decode($res->getBody(), TRUE);

Many thanks for any help on this.

UPDATE-ANSWER

$res = 'http://api.yummly.com/v1/api/recipes?_app_id=MY_ID&_app_key=MY_KEY&q='.$query;

        if($include) {
        $res .= '&allowedIngredient[]='.$include;
        }

        if($include2) {
         $res .= '&allowedIngredient[]='.$include2;
        }

        if($include3) {
         $res .= '&allowedIngredient[]='.$include3;
        }

        if($exclude) {
         $res .= '&excludedIngredient[]='.$exclude;
        }

        if($exclude2) {
         $res .= '&excludedIngredient[]='.$exclude2;
        }

        $res .='&requirePictures=true&maxResult=50';
        $result = $client->get($res , ['auth' =>  ['user', 'pass']]);
        $body = json_decode($result->getBody(), TRUE);

Upvotes: 0

Views: 509

Answers (1)

Ne Ma
Ne Ma

Reputation: 1709

Easiest method is to just check for a valid value.

$apiUrl = 'http://api.yummly.com/v1/api/recipes?_app_id='MY_ID'&_app_key='MY_KEY'&q='.$query;

if($include) {
    $apiUrl .= '&allowedIngredient[]='.$include;
}

if($include2) {
    $apiUrl .= '&allowedIngredient[]='.$include2;
}

// Etc for all vars

You can also do it by building an array and then imploding it, but this would be quite messy as the keys would need '$allowedIngredient[]' so will let you investigate that route.

Upvotes: 1

Related Questions