通过curl和进程响应进行Shell脚本调用API

时间:2019-05-21 06:54:14

标签: shell curl jwt

我需要创建一个shell脚本,该脚本通过curl调用我的登录API。 该脚本应该能够存储和处理来自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. 它没有得到curl调用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调用中将令牌值用作承载令牌。

要从curl api调用的响应中提取token值,我需要在脚本中进行哪些更改?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

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

当从脚本执行curl时,无声的-s标志也有帮助:

  

-s,--silent   静音或安静模式。不要显示进度表或错误消息。使Curl静音。

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

完整的脚本如下所示:

#!/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

答案 1 :(得分:0)

使用正则表达式解析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'