Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 872
Bercovici Adrian Avatar asked Dec 27 '18 10:12

Bercovici Adrian


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

Can we use curl command in shell script?

The curl command transfers data to or from a network server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE). It is designed to work without user interaction, so it is ideal for use in a shell script.


1 Answers

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

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.

like image 190
edaemon Avatar answered Sep 19 '22 03:09

edaemon