gpt4 book ai didi

Shell脚本通过curl调用API并处理响应

转载 作者:行者123 更新时间:2023-12-02 03:15:36 24 4
gpt4 key购买 nike

我需要创建一个通过curl 调用我的登录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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64001109091d491117011624050709014a070b09" rel="noreferrer noopener nofollow">[email protected]</a>", "password": "secret"}'

curl -s --request POST -H "Content-Type:application/json" http://acme.com/api/authentications/login --data "${PAYLOAD}"

给定脚本中我的问题是:

  1. 没有得到curl调用API的响应。
  2. 从响应 json 中,仅获取 token 值。

示例登录 API 响应:

{
"user": {
"id": 123,
"token": "<GENERATED-TOKEN-HERE>",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c7d6ceceda8ed6d0c6d1e3c2c0cec68dc0ccce" rel="noreferrer noopener nofollow">[email protected]</a>",
"refreshToken": "<GENERATED-REFRESH-TOKEN>",
"uuid": "1239c226-8dd7-4edf-b948-df2f75508888"
},
"clientId": "abc12345",
"clientSecretKey": "thisisasecret"
}

我只需要获取token的值并将其存储在一个变量中...我将在其他curl api调用中使用token值作为不记名 token 。

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

谢谢!

最佳答案

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

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 Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute.

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

完整的脚本可能如下所示:

#!/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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04607169697d297177617644656769612a676b69" rel="noreferrer noopener nofollow">[email protected]</a>", "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

关于Shell脚本通过curl调用API并处理响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56232676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com