如何使API具有必需参数和可选参数|的PHP

假设有一个自定义API来获取giftcode。

API具有引用 Amount 作为必需参数,而已激活数量作为可选参数

如果URL为:

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

它应该在默认情况下假设已激活且数量为1的情况下运行

如果URL为:

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

值应为url中提供的值,而不是默认值。

我们如何使用php做到这一点? (我的平台是Magento 2)

cuijuncyanway 回答:如何使API具有必需参数和可选参数|的PHP

此验证可以在服务器端进行。将其作为PHP实用程序。

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

    }
}

$ _ GET中可用的查询参数。

,

使用Null coalescing operator (??)获取数组中不存在的key-value的默认值。例如:

$quantity = $_GET['quantity'] ?? 1;
$activated = $_GET['activated'] ?? 1;
本文链接:https://www.f2er.com/3146035.html

大家都在问