HTTP Request in Shell

Level 5245 keystrokes

curl fetches a URL and appends the HTTP status code on a last line with -w; the script then splits that line from the body, and if the status is 200 it extracts the name field with jq. The output depends on the server's response.

Shell code

# -s hides the progress bar; -w adds a newline and the status code after the body
1response=$(curl -s -w "\n%{http_code}" "https://api.example.com/data")
# The last line is the status code
2http_code=$(echo "$response" | tail -n1)
# sed '$d' deletes the last line, leaving only the body
3body=$(echo "$response" | sed '$d')
# -eq compares numbers: 200 means OK
4if [[ $http_code -eq 200 ]]; then
# Extract the name field from the JSON body (printed with quotes)
5 echo "$body" | jq '.name'
6else
# Any other status is reported as an error
7 echo "Error: HTTP $http_code"
8fi

Output

"John Doe"
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 12
  • $× 9
  • _× 4
  • -× 4
  • '× 4
  • .× 3
  • (× 3
  • )× 3
  • /× 3
  • =× 3

More Shell examples at level 5

← Shell typing practice