Bercovici Adrian
Bercovici Adrian

Reputation: 9360

Sending POST Request from bash script

I want to execute a bash script after i make a POST request.So far i am using Postman for sending the request , but i was wondering if i can somehow do it from a bash script as well with a json file as parameter.

I have looked into curl so far but it does not work:

bash file

curl -X POST -d req.json http://localhost:9500

Json file (req.json)

{
    "id":5,
    "name":"Dan",
    "age":33,
    "cnp":33,
    "children":100,
    "isMarried":0
}

I just get the error :

HTTP/1.0 503 Service Unavailable

with the trailing HTML

Upvotes: 31

Views: 71374

Answers (1)

edaemon
edaemon

Reputation: 939

curl should do the job. This will send a normal POST request using the data in req.json as the body:

curl -X POST -H 'Content-Type: application/json' -d @req.json http://localhost:9500
curl -X POST -H 'Content-Type: application/json' -d '{"message": "hello"}' http://localhost:9500

The elements you were missing are -H "Content-Type: application/json" and the @ in the data flag. Without the -H flag as above curl will send a content type of application/x-www-form-urlencoded, which most applications won't accept if they expect JSON. The @ in the -d flag informs curl that you are passing a file name; otherwise it uses the text itself (i.e. "req.json") as the data.

Upvotes: 40

Related Questions