- Making a POST Request with a JSON Payload using Curl
- Как сделать POST-запрос с помощью cURL
- Выполнение запроса POST
- Указание Content-Type
- Загрузка файлов
- Выводы
- POST JSON data with cURL
- [#post-a-json-file]cURL POST a JSON file[#post-a-json-file]
- [#json-option]cURL with —json[#json-option]
- [#format-json]Make sure you format your JSON correctly[#format-json]
- [#double-quotes-inside-single-quotes]Use double quotes inside single quotes[#double-quotes-inside-single-quotes]
- [#enquote-or-escape-special-chars]Escape or enquote special characters in the URL[#enquote-or-escape-special-chars]
- [#charset-in-content-type]The server may require a charset in the content-type[#charset-in-content-type]
- [#405-error-on-post]Solving HTTP status code 405 (Method Not Allowed)[#405-error-on-post]
- How to do HTTP-request/call with JSON payload from command-line?
- 5 Answers 5
Making a POST Request with a JSON Payload using Curl
The `curl` command line utility is a powerful tool for making HTTP requests. It can be used to send a variety of different HTTP requests, including POST requests with a JSON body. Here’s how you can use curl to send a POST request with a JSON body:
Create a JSON file that contains the data you want to send in the request body. For example, let’s say you have a file named `data.json` with the following contents:
Use the curl command to send a POST request with the JSON data. The `-X` option specifies the request method (in this case, POST), and the `-H` option adds an HTTP header (in this case, `Content-Type: application/json` to specify that the request body is in JSON format). The -d option specifies the request body, and the `@` symbol tells curl to read the data from a file. Here’s the command to send the POST request with the JSON data:
curl -X POST -H "Content-Type: application/json" -d @data.json http://example.com/endpoint
If the request is successful, the server will return a response. You can use the `-i` option to include the response headers in the output, or the `-o` option to save the response to a file. Here’s an example of using the `-i` option to print the response headers:
curl -X POST -H "Content-Type:application/json" -d @data.json http://example.com/endpoint -i
curl -X POST -H "Content-Type: application/json" -d @data.json http://example.com/endpoint -o response.txt
That’s all there is to it! With these simple commands, you can use `curl` to send a POST request with a JSON body to a server.
Keep in mind that the JSON data in the request body must be properly formatted and valid, or the request may fail. You can use a tool like JSONLint (https://jsonlint.com/) to validate your JSON data before sending it in the request.
I hope this tutorial has been helpful in showing you how to use `curl` to send a POST request with a JSON body. If you have any questions or need further assistance, don’t hesitate to ask.
Как сделать POST-запрос с помощью cURL
cURL — это утилита командной строки для передачи данных с или на удаленный сервер с использованием одного из поддерживаемых протоколов. Он установлен по умолчанию в macOS и большинстве дистрибутивов Linux.
cURL используется разработчиками для тестирования API , просмотра заголовков ответов и выполнения HTTP-запросов.
В этой статье мы собираемся объяснить, как использовать cURL для выполнения запросов POST. Метод HTTP POST используется для отправки данных на удаленный сервер.
Выполнение запроса POST
Общая форма команды curl для выполнения запроса POST следующая:
Тип тела запроса указывается его заголовком Content-Type .
Обычно запрос POST отправляется через HTML-форму. Данные, отправляемые в форму, обычно кодируются в типе содержимого multipart/form-data или application/x-www-form-urlencoded .
Чтобы создать запрос POST, используйте параметр -F , за которым следует пара field=value . В следующем примере показано, как отправить POST-запрос в форму с полями «имя» и «электронная почта»:
curl -X POST -F 'name=linuxize' -F '[email protected]' https://example.com/contact.php
Когда используется опция -F , curl отправляет данные с использованием Content-Type multipart/form-data .
Другой способ сделать запрос POST — использовать параметр -d . Это заставляет curl отправлять данные с использованием Content-Type application/x-www-form-urlencoded Content-Type.
curl -X POST -d 'name=linuxize' -d '[email protected]' https://example.com/contact.php
Если параметр -d используется более одного раза, вы можете объединить данные с помощью символа & :
curl -X POST -d 'name=linuxize&[email protected]' https://example.com/contact.php
Указание Content-Type
Чтобы установить определенный заголовок или Content-Type, используйте параметр -H . Следующая команда устанавливает тип запроса POST на application/json и отправляет объект JSON:
Загрузка файлов
Чтобы отправить файл с помощью curl , просто добавьте символ @ перед местоположением файла. Файл может быть архивом, изображением, документом и т. Д.
curl -X POST -F 'image=@/home/user/Pictures/wallpaper.jpg' http://example.com/upload
Выводы
Мы показали вам, как использовать curl для выполнения запросов POST. Дополнительные сведения о curl см. На странице документации по Curl .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
POST JSON data with cURL
cURL is an excellent tool for interacting with applications over HTTP and HTTPS. In this post, we will cover how to send JSON to a web server via cURL and review some possible gotchas you might run into when constructing the payload.
Digging into the legacy example from above:
curl -X POST -H ‘Content-Type: application/json’ \ -d ‘’ https://myendpoint.com/message
Take note how in the above example we construct the JSON payload directly on the command line, and pass the [.inline-code]Content-Type[.inline-code] header to [.inline-code]application/json[.inline-code] to allow our server to understand that what we are sending is in JSON format.
[#post-a-json-file]cURL POST a JSON file[#post-a-json-file]
Sometimes, we cannot construct the JSON directly on the command line as shown above. Perhaps the payload is very large or requires complex constructs such as nested arrays. In this scenario it would be preferable to construct the JSON using another method (e.g. a Python script) and dump it into a file. Then, when the JSON file is in place, we can send it via cURL.
# assume your file is named test.json curl -X POST -H ‘Content-Type: application/json’ -d @test.json https://myendpoint.com/message
[#json-option]cURL with —json[#json-option]
With the March 2022 release of cURL version 7.82.0, a new [.inline-code]—json[.inline-code] option became available. Back to the example from the top:
$ curl --json ‘’ https://myendpoint.com/message
Take note that we don’t need to pass the [.inline-code]Content-Type[.inline-code] header, nor the [.inline-code]-X POST[.inline-code]. cURL handles these bits internally as a result of [.inline-code]—json[.inline-code].We can further shorten the above by putting our JSON in a file called test.json and running this command:
$ curl --json @test.json https://myendpoint.com/message
[#format-json]Make sure you format your JSON correctly[#format-json]
It is recommended to pass your intended JSON payload through jq to verify the syntax. For example:
$ echo '' | jq # or $ cat test.json | jq
[#double-quotes-inside-single-quotes]Use double quotes inside single quotes[#double-quotes-inside-single-quotes]
If building JSON on the command line, keep in mind single quotes on the outside and double quotes on the inside. For example:
$ curl --json ‘’ https://myendpoint.com/message
[#enquote-or-escape-special-chars]Escape or enquote special characters in the URL[#enquote-or-escape-special-chars]
# use quotes when trying to do curl --json https://myendpoint.com&hello $ curl --json “https://myendpoint.com&hello” # or escape it $ curl https://myendpoint.com\&hello
[#charset-in-content-type]The server may require a charset in the content-type[#charset-in-content-type]
If so, you can pass it like this:
$ curl --json ‘’ \ -H "Content-Type: application/json; charset=UTF-8" https://myendpoint.com/message
[#405-error-on-post]Solving HTTP status code 405 (Method Not Allowed)[#405-error-on-post]
This means that an HTTP POST is not accepted on the endpoint. Try another method, such as PUT or PATCH, that aligns with the API specification of the server you are trying to hit.
This post was all about cURL with JSON payloads — read more about cURL POST requests more generally in our other post.
How to do HTTP-request/call with JSON payload from command-line?
What’s the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data. The Request Payload as shown in Google Chrome looks like this:
It’s about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.
5 Answers 5
You could use wget as well:
wget -O- --post-data='' \ --header='Content-Type:application/json' \ 'http://www.example.com:9000/json'
Calling wget with the option -O providing the — (space in between will be ignored, so it could also be written as -O — ) to it as its value will cause wget to output the HTTP response directly to standard output instead into a file. The long option name for that is —output-document=file .
From the man page -O file is the shorthand option for —output-document=file and the dash ( — ) usually represents the file descriptor for standard out of the current tty. It just means «print the result to the console instead of writing it to a file».
Thanks. My point is that this argument looks cryptic, I would suggest to add this explanation to the answer 😉
@SlavaFominII thanks for pointing that out. I’ve updated the answer to contain an explanation about the -O option.
Use curl, assuming the data is POST’ed, something like
curl -X POST http://example.com/some/path -d ' >'
If you’re just retrieving the data with a GET , and don’t need to send anything bar URL parameters, you’d just run curl http://example.com/some/path
You could use wget with post-file as well, which I found useful.
wget --post-file=[file] --header=Content-Type:application/json [URL]
You can keep the content in the file and the content will be sent as post data.
curl --request POST \ --url http://localhost:8099/someservice/services/boo \ --header 'authorization: Basic dkfhsdlepwmdseA==' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ --data ''
Have you looked at curl? It’s very good at facilitating HTTP GET/POST requests via the command line.
C:\WINDOWS>curl "http://search.twitter.com/search.json?q=twitterapi&result_type= popular" <"results":[<"from_user_id_str":"32316068","profile_image_url":"http://a2.twimg. com/profile_images/351010682/twitblock_profile_normal.png","created_at":"Thu, 25 Nov 2010 14:37:46 +0000","from_user":"twitblockapp","id_str":"7805146834669569" ,"metadata":<"result_type":"popular","recent_retweets":10>,"to_user_id":null,"te xt":"blocking and reporting functions are currently failing. @TwitterAPI have be en notified. http://j.mp/id5w3m","id":7805146834669569,"from_user_id":32316068," geo":null,"iso_language_code":"en","to_user_id_str":null,"source":"<a href=&q uot;http://twitter.com" rel="nofollow">Tweetie for Mac</a&g t;">],"max_id":9607558079713280,"since_id":0,"refresh_url":"?since_id=9607558079 713280&q=twitterapi","results_per_page":15,"page":1,"completed_in":0.012698,"sin ce_id_str":"0","max_id_str":"9607558079713280","query":"twitterapi">