-1

Suppose there is a custom API to get giftcode.

The API has Referance and Amount as requird parameters whereas Activated and Quantity as optional parameters

If URL is:

http://ruteurl/rest/V1/giftcode/request?reference=XYZ&amount=50

It should run assuming Activated and Quantity to be 1 by default

If URL is:

http://ruteurl/rest/V1/giftcode/request?reference=XYZ&amount=50&activated=0&quantity=5

the values shoud be as provided in url and not the default ones.

How can we do this using php? (My platform is Magento 2)

Ajwad Syed
  • 335
  • 2
  • 15
  • 1
    Check if the GET-parameter is set, if not set a default value – empiric Nov 07 '19 at 09:44
  • @empiric can you share an example or link for setting GET-parameter, BTW I am using POST method to create API – Ajwad Syed Nov 07 '19 at 09:47
  • You don't set GET-parameters, you set a variable with a value from the get parameter (or not): `$qty = isset($_GET['qunatitiy']) ? $_GET['qunatitiy'] : 1;` – empiric Nov 07 '19 at 09:50

2 Answers2

2

Use the Null coalescing operator (??) to get a default value for a non-existing key-value in an array. For example:

$quantity = $_GET['quantity'] ?? 1;
$activated = $_GET['activated'] ?? 1;
Chemaclass
  • 1,933
  • 19
  • 24
0

This validation can be done in the server side. Make it as a PHP utility.

function validate_query_params($query_params)
{
    foreach($query_params as $key => &$value)
    {
        // Check for mandator params 
        // If any mandatory params missing, echo/print response with error 

        // else proceed with optional params. Use default values if missing

    }
}

Query params available in $_GET.

J L P J
  • 442
  • 3
  • 8