Shell Script通过卷曲和过程响应调用API



我需要创建一个通过卷曲来调用我的登录API的shell脚本。该脚本应该能够存储和处理Curl API调用的响应。

myScript.sh

#!/bin/bash
echo "Extract bearer token from curl calling login api"
echo
# Check cURL command if available (required), abort if does not exists
type curl >/dev/null 2>&1 || { echo >&2 "Required curl but it's not installed. Aborting."; exit 1; }
echo
PAYLOAD='{"email": "dummy-user@acme.com", "password": "secret"}'
curl -s --request POST -H "Content-Type:application/json"  http://acme.com/api/authentications/login --data "${PAYLOAD}"

我在给定脚本中的问题是:

  1. 它没有得到卷曲调用API的响应。
  2. 从响应json中,仅获取令牌值。

示例登录API响应:

{
  "user": {
    "id": 123,
    "token": "<GENERATED-TOKEN-HERE>",
    "email": "dummy-user@acme.com",
    "refreshToken": "<GENERATED-REFRESH-TOKEN>",
    "uuid": "1239c226-8dd7-4edf-b948-df2f75508888"
  },
  "clientId": "abc12345",
  "clientSecretKey": "thisisasecret"
}

我只需要获取 token的值并将其存储在变量中...我将在其他curl api调用中使用令牌值作为承载令牌。

我需要更改脚本以从卷曲API调用的响应中提取token值?

谢谢!

您的curl语句中有一个错误。您正在用目标URL作为标头字段执行它:

curl --request POST -H "Content-Type:application/json" -H http://acme.com/api/authentications/login --data "${PAYLOAD}"
                                                       ^
                                                       |
                                                   Remove this header flag

还从脚本执行卷曲时,静音-s标志有助于:

-s,-silent 沉默或安静的模式。不要显示进度计或错误消息。使卷曲静音。

之后,您可以将数据存储在变量中并在其上执行正则表达式以提取您需要进一步处理所需的令牌。

完整的脚本看起来如下:

#!/bin/bash
echo "Extract bearer token from curl calling login api"
echo
# Check cURL command if available (required), abort if does not exists
type curl >/dev/null 2>&1 || { echo >&2 "Required curl but it's not installed. Aborting."; exit 1; }
echo
PAYLOAD='{"email": "dummy-user@acme.com", "password": "secret"}'
RESPONSE=`curl -s --request POST -H "Content-Type:application/json" http://acme.com/api/authentications/login --data "${PAYLOAD}"`
TOKEN=`echo $RESPONSE | grep -Po '"token":(W+)?"K[a-zA-Z0-9._]+(?=")'`
echo "$TOKEN" # Use for further processsing

用正则分析JSON的替代解决方案是JQ:

echo '{ "user": { "id": 123, "token": "<GENERATED-TOKEN-HERE>", "email": "dummy-user@acme.com", "refreshToken": "<GENERATED-REFRESH-TOKEN>", "uuid": "1239c226-8dd7-4edf-b948-df2f75508888" }, "clientId": "abc12345", "clientSecretKey": "thisisasecret" }' | jq -r '.user.token'

最新更新