Search code examples
jsonbashhttp-post

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


Solution

  • 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.