I'd like to prepare a test for a REST petstore server by the mean of curl
.
To test its add new pet
api, I prepare a json string that holds the Pet
to insert in a bash function that executes the curl
:
#!/bin/bash
# Add new pet
add_petstore() {
local rest_url="$1"
local id_pet="$2"
local id_category="$3"
local category_name="$4"
local pet_name="$5"
local photo_url="$6"
local tag_id="$7"
local tag_name="$8"
local pet_to_add="{ \
\"id\": $id_pet, \
\"category\": { \
\"id\": $id_category, \
\"name\": \"$category_name\" \
}, \
\"name\": \"$pet_name\", \
\"photoUrls\": [ \
\"$photo_url\" \
], \
\"tags\": [ \
{
\"id\": $tag_id, \
\"name\": \"$tag_name\" \
} \
] \
}"
echo "$pet_to_add"
curl -X 'POST' \
"$rest_url" \
-H 'accept: application/xml' \
-H 'Content-Type: application/json' \
-d "$pet_to_add"
}
add_petstore "http://localhost:8080/pet" "151" "12" "Dogs" "REX" "http://photosofrex/rex_rage.jpg" "1" "ferocious sales"
The echo
of $pet_to_add
looks the one I willing to have:
{ "id": 151, "category": { "id": 12, "name": "Dogs" }, "name": "REX", "photoUrls": [ "http://photosofrex/rex_rage.jpg" ], "tags": [ {
"id": 1, "name": "ferocious sales" } ] }
and add_petstore
method allows me to prepare few pets easily.
But the local pet_to_add=...
declaration is really dirty.
If someone (or me later) has to adapt this script, this local variable isn't welcoming.
I thought first that I could put its content in a file and read it with a local pet_to_add=$(cat myfile)
. But this wouldn't resolve it's variable parameters then.
Do I have a way to write that local pet_to_add
declaration a cleaner way?
jq
to update it with env variables?jq
method of Kusalananda is safer, it's quite cumbersome. Is there a specific reason you're using bash? It would be sooooo much simpler with node.js, perl, php, and probably many other languages with support for associative arrays and JSON encoding.rest_url
should also use quotes around"$1"
hello"},{"id":"evil","name":"secondpet
-- if records represent, say, accounts being created, someone could create a second account with arbitrary settings by creating a huge name in their one legit account). You're much better off withjq --arg
.