How to capture a curl http status code in a GitHub Action to determine success/failure?

Viewed 6354

I am very new to GitHub Actions so bear with me...I am trying to create a GitHub Action, with one of the steps being a curl call to a GitHub API. I want to catch the HTTP status code, for that curl call, to determine if the Action actually failed or not. Right now, because the curl completes successfully, it always returns as a successful run, even if the curl response may have a bad status code (e.g. 405, 404, 403, etc).

Here is my curl call:

- name: Squash And Merge After Approval of PR
        run: |
          curl --request PUT \
          --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
          --header 'content-type: application/json' \
          --url https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.inputs.pr_num }}/merge \
          --data '{
           "merge_method": "squash",
           "commit_title": "Squash and Merge for Pull Request ${{ github.event.inputs.pr_num }}",
           "commit_message": "expected sha value = ${{ github.event.inputs.pr_head_sha }}",
           "sha":"${{ github.event.inputs.pr_head_sha }}"
           }'

I'm thinking I have to wrap my curl command somehow to maybe output the response in a variable, or? But I don't know how to capture the curl response, parse it, and check the status code to determine if curl was successful or not.

TIA.

PS: This is a manually run Action, therefore I am supplying the "sha" and "pr number" from an input form when the Action is run.

1 Answers

This answer relates to your curl question - a way you could capture the code response as a string.

CODE=`curl --write-out '%{http_code}' \
    --silent \
    --output /dev/null \
    --request PUT \
    --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' \
    --header 'content-type: application/json' \
    --url 'https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.inputs.pr_num }}/merge' \
    --data '{ \
    "merge_method": "squash", \
    "commit_title": "Squash and Merge for Pull Request ${{ github.event.inputs.pr_num }}", \
    "commit_message": "expected sha value = ${{ github.event.inputs.pr_head_sha }}", \
    "sha":"${{ github.event.inputs.pr_head_sha }}" \
    }'`

if [ $CODE!="200" ] 
then
    echo "FAILURE"
else
    echo "SUCCESS"
fi

However, if the request fails the curl command should return a failure code

EX:

if curl "..."
then echo "SUCCESS"
else echo "FAILURE"
fi
Related