首页 > 解决方案 > Check json field from the curl response in linux

问题描述

I am writing a script in gitlab-ci file and the server I am using is Linux to run the pipeline.

Now I want to make two API call and 2nd call is dependent on the 1st

for example

URL= you can take any HTTPS endpoint (i guess it really doesn't matter)

jsonResponse=$(curl -d $requestJson -X POST $FIRST_URL)

echo $jsonResponse

[{"result":"Success"}]

Based on the result field (success/failure) I want to make another API call using curl. something like below

if response[0].result=success then "curl -d $requestJson -X POST $SECOND_URL" else exit 1

Note that the response will be in Array.

标签: linuxgitlab-cialpine

解决方案


What you could possibly do is that you will save the output from 1st API call to a file (api1-output.json) and then pass it to the next correspondent job from where you can read that output and act based on its response.

Example in your .gitlab-ci.yml file:

api1_execution:
   image: your_image
   script:
      - curl -XGET https://my-api1-endpoint.com/api/getSomething > scripts/api1-output.json
   artifacts:
      paths:
         - scripts/api1-output.json


api2_execution:
   image: your_image
   script:
      - API1_OUTPUT= $(cat scripts/api1-output.json)
      - // do whatherever you want with API1_OUTPUT
      - // fire 2nd API call

For parsing and reading JSON output I highly recommend that you use tool called jQ

The above example can serve to you just as an idea how it can be done from my perspective.


推荐阅读