Linux curl post запрос json

How To POST JSON data with Curl Command Line

Question- How to POST JSON data with curl? How to POST JSON data with curl command line? How do I POST JSON data on Linux terminal?

You can add -H «Content-Type: application/json» header value to Post the JSON data to curl command line.

For example, I have an API URL https://api.example.com/v2/login , that is used to authenticate the application. Now passing the username and password in JSON format using the curl command line tool.

You can also write the username and password in a user.json file. Now use this file to pass the JSON data to curl command line.

How to Scan Open Ports with Nmap

Handling filenames with spaces in Linux

How To Compare Two Files in Linux

5 Comments

how to use “Authentication: XXX”?

I have a case as bellows:
curl -u admin:admin123 -X POST -H ‘Content-Type: application/json’ -d “@a.json” “http://abc.net:7180/api/v33/clusters/CDH_5.14/services/hdfs/snapshots/policies/hdfs_snapshot_p3”

But got 405 error. how to fix it? # grep hdfs_snapshot_p3 cloudera-scm-server.log
2021-01-22 16:44:50,176 INFO scm-web-1371570:com.cloudera.enterprise.JavaMelodyFacade: Entering HTTP Operation: Method:POST, Path:/v33/clusters/CDH_5.14/services/hdfs/snapshots/policies/hdfs_snapshot_p3
2021-01-22 16:44:50,183 INFO scm-web-1371570:com.cloudera.enterprise.JavaMelodyFacade: Exiting HTTP Operation: Method:POST, Path:/v33/clusters/CDH_5.14/services/hdfs/snapshots/policies/hdfs_snapshot_p3, Status:405
I google online, some webpage said not to Allow POST. do not know how to do that. Can anyone help?

Thank you. I’ve been looking for a solution to loading a JSON file into a curl command for days – this has fixed it.
Thank you again!

Источник

Как сделать POST-запрос с помощью cURL

cURL — это утилита командной строки для передачи данных с или на удаленный сервер с использованием одного из поддерживаемых протоколов. Он установлен по умолчанию в macOS и большинстве дистрибутивов Linux.

cURL используется разработчиками для тестирования API , просмотра заголовков ответов и выполнения HTTP-запросов.

В этой статье мы собираемся объяснить, как использовать cURL для выполнения запросов POST. Метод HTTP POST используется для отправки данных на удаленный сервер.

Выполнение запроса POST

Общая форма команды curl для выполнения запроса POST следующая:

Читайте также:  Avast free antivirus 2020 для windows

Тип тела запроса указывается его заголовком Content-Type .

Обычно запрос POST отправляется через HTML-форму. Данные, отправляемые в форму, обычно кодируются в типе содержимого multipart/form-data или application/x-www-form-urlencoded .

Чтобы создать запрос POST, используйте параметр -F , за которым следует пара field=value . В следующем примере показано, как отправить POST-запрос в форму с полями «имя» и «электронная почта»:

Когда используется опция -F , curl отправляет данные с использованием Content-Type multipart/form-data .

Другой способ сделать запрос POST — использовать параметр -d . Это заставляет curl отправлять данные с использованием Content-Type application/x-www-form-urlencoded Content-Type.

Если параметр -d используется более одного раза, вы можете объединить данные с помощью символа & :

Указание Content-Type

Чтобы установить определенный заголовок или Content-Type, используйте параметр -H . Следующая команда устанавливает тип запроса POST на application/json и отправляет объект JSON:

Загрузка файлов

Чтобы отправить файл с помощью curl , просто добавьте символ @ перед местоположением файла. Файл может быть архивом, изображением, документом и т. Д.

Выводы

Мы показали вам, как использовать curl для выполнения запросов POST. Дополнительные сведения о curl см. На странице документации по Curl .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How do I POST JSON with Curl?

Compare Request Timings

What is Curl?

Curl is a popular command-line software for transferring data to or from the server using URL syntax. Curl supports many protocols, including HTTP, HTTPS, FTP, SFTP, and works on all modern platforms and hardware, including Linux, Windows, and macOS.

What is JSON?

JSON (JavaScript Object Notation) is a standard textual format for representing structured data based on the syntax of a JavaScript object. JSON is widely used for client/server communication, transferring data to and from the server in web and mobile applications.

What is HTTP POST?

POST is one of the most widely used methods of the HTTP protocol. The POST method requests the webserver to receive and process the data enclosed in the body of the POST message. The POST method is often used to upload files and submit HTML forms.

How to make a POST request with Curl?

There are two ways to send a POST request with Curl.

  1. When you use command-line parameters such as —data or —form and do not explicitly specify the required HTTP method, Curl automatically selects the POST method and sends a POST request with the application/x-www-form-urlencoded content type (or multipart/form-data for —form).
  2. Explicitly specify the required HTTP method using the -X command-line argument. For example, you need to use the -X POST-command-line parameter to send JSON using the POST method.

Curl POST Request Syntax

The general form of a Curl command for making a POST request with a JSON body is as follows:

Why do I need to explicitly specify the Content-Type when posting JSON using Curl?

If you submit data using Curl and do not explicitly specify the Content type, Curl uses the application/x-www-form-urlencoded content type for your data. Therefore, when sending JSON (or any other data type), you must specify the data type using the explicitly -H «Content-Type: application/json» command line parameter.

Читайте также:  Windows 10 альтернативный интерфейс

Why is it important to specify the correct Content-Type when submitting JSON?

In short, if you don’t set the correct Content-Type, your application may not work. The Content-Type header field indicates the media type included in the message payload. The specified media type determines both the format of the data and the way the server handles that data.

For example, if the server can accept XML and JSON data on the same API endpoint, setting the Content-Type to application/json will let the server know that the client is sending JSON data, and application/xml will tell the server that the client is sending XML.

How to post JSON file with Curl?

You can post a JSON file using Curl if you pass the filename in the -d command line parameter after the «@» symbol:

See also

Generate Code Snippets for Curl POST JSON Example

Convert your Curl POST JSON request to the PHP, JavaScript/AJAX, Curl/Bash, Python, Java, C#/.NET code snippets using the ReqBin code generator.

Источник

Using curl POST with variables defined in bash script functions

When I echo I get this, which runs when I enter it into the terminal

But when run in the bash script file, I get this error

this is the code in the file

I assume there’s an issue with my quotation marks, but I’ve played with them a lot and I’ve gotten similar errors. All the variables are defined with different functions in the actual script

9 Answers 9

You don’t need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the data argument should be quoted.

First, write a function that generates the post data of your script. This saves you from all sort of headaches concerning shell quoting and makes it easier to read an maintain the script than feeding the post data on curl’s invocation line as in your attempt:

It is then easy to use that function in the invocation of curl:

This said, here are a few clarifications about shell quoting rules:

The double quotes in the -H arguments (as in -H «foo bar» ) tell bash to keep what’s inside as a single argument (even if it contains spaces).

The single quotes in the —data argument (as in —data ‘foo bar’ ) do the same, except they pass all text verbatim (including double quote characters and the dollar sign).

To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: ‘foo bar'»$variable»‘more foo’ .

Читайте также:  Intel 4965agn windows 10 драйвера

Источник

Использование Curl для выполнения запросов REST API

Интерфейс прикладных программ (API) — это набор определений и протоколов, которые позволяют программам взаимодействовать друг с другом.

Термин REST означает передачу репрезентативного состояния. Это архитектурный стиль, состоящий из набора ограничений, используемых при создании веб-сервисов.

RESTful API — это API, который следует архитектуре REST. Обычно API-интерфейсы REST используют протокол HTTP для отправки и получения данных и ответов в формате JSON. Вы можете использовать стандартные методы HTTP для создания, просмотра, обновления или удаления ресурсов через API.

Для тестирования API RESTful и взаимодействия с ними вы можете использовать любую библиотеку или инструмент, который может выполнять HTTP-запросы.

Запросы API состоят из четырех разных частей:

  • Конечная точка. Это URL-адрес, который клиент использует для связи с сервером.
  • Метод HTTP. Он сообщает серверу, какое действие хочет выполнить клиент. Наиболее распространенные методы — GET POST PUT DELETE и PATCH
  • Заголовки. Используется для передачи дополнительной информации между сервером и клиентом, например авторизации.
  • Тело. Данные отправлены на сервер.

В этой статье мы собираемся обсудить, как использовать curl для взаимодействия с RESTful API. curl — это утилита командной строки для передачи данных с или на удаленный сервер. Он установлен по умолчанию в macOS и большинстве дистрибутивов Linux.

Параметры завивки

Синтаксис команды curl следующий:

Вот параметры, которые мы будем использовать при выполнении запросов:

  • -X , —request — HTTP-метод, который будет использоваться.
  • -i , —include — включить заголовки ответа.
  • -d , —data — данные для отправки.
  • -H , —header — дополнительный заголовок для отправки.

HTTP GET

Метод GET запрашивает у сервера определенный ресурс.

GET — это метод по умолчанию при выполнении HTTP-запросов с помощью curl . Вот пример выполнения запроса GET к API JSONPlaceholder для представления JSON всех сообщений:

Для фильтрации результатов используйте параметры запроса:

HTTP POST

Метод POST используется для создания ресурса на сервере. Если ресурс существует, он перезаписывается.

Следующая команда выполняет запрос POST, используя данные, указанные с параметром -d :

Тип тела запроса указывается с помощью заголовка Content-Type . По умолчанию, когда этот заголовок не задан, curl использует Content-Type: application/x-www-form-urlencoded .

Чтобы отправить данные в формате JSON, установите тип тела в application/json :

HTTP PUT

Метод PUT используется для обновления или замены ресурса на сервере. Он заменяет все данные указанного ресурса данными запроса.

HTTP-ПАТЧ

Метод PUT используется для частичного обновления ресурса на сервере.

HTTP УДАЛИТЬ

Метод DELETE удаляет указанный ресурс с сервера.

Аутентификация

Если конечная точка API требует аутентификации, вам необходимо получить ключ доступа. В противном случае сервер API ответит ответным сообщением «Доступ запрещен» или «Неавторизован».

Процесс получения ключа доступа зависит от API, который вы используете. Получив токен доступа, вы можете отправить его в заголовке:

Выводы

Мы показали вам, как использовать curl для выполнения тестовых запросов API. Дополнительные сведения о curl см. На странице документации по Curl .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Оцените статью