Как вставить curl в postman
Last Modified: August 12, 2020
In this tutorial, we’ll learn how to generate Curl command using Postman.
Overview
Many times we need to execute GET, POST, PUT, PATCH, DELETE Http requests to verify endpoints. Normally we use:
There are many times where we stuck in a situation where:
In such cases Curl command is very useful which can be used to execute HTTP endpoints from command prompt or terminal.
Installing Curl
The curl package is pre-installed on most Linux distributions today.
If curl is not installed you can easily install it using the package manager of your distribution.
Install Curl on Ubuntu and Debian
Install Curl on CentOS and Fedora
Generate Curl from Postman
Considering that you are already familiar with Postman. Follow these steps:
Create HTTP request using Postman
Click on the Code button.
A dialog “GENERATE CODE SNIPPET” will appear. Select “cURL” from the dropdown.
You can copy the command using Copy to Clipboard button.
Please note that Postman generate multi-line CURL command which works in Mac and Linux environment but not in windows terminal. In such cases, you need to change command to single-line manually.
Имитация определенного CURL в PostMan
Я использую Postman для проверки некоторых запросов Curl к серверу API. Разработчики API дали нам команду curl, но я не могу ее отправить из почтальона. Как сделать такой запрос от Почтальона?
Более простой подход:
Надеюсь это поможет!
1) Поместите https://api-server.com/API/index.php/member/signin в поле ввода URL-адреса и выберите POST из раскрывающегося списка
2) На вкладке Заголовки введите:
Тип содержимого: изображение / JPEG
3) На вкладке Body выберите raw переключатель и напишите:
выберите form-data переключатель и напишите:
key = name Value = userfile Выберите Text key = filename Выберите File и загрузите ваш profil.jpg
Я пробовал подход, упомянутый Онкааром Сингхом,
Но проблема в том, что это не сработало для Apis, который требует авторизации.
Это был мой запрос на завиток:
После импорта тело было импортировано правильно, заголовки и URL-адрес также были импортированы. Только ключ api 9f4d7f5445e7, который
в запросе curl не импортировал.
Надеюсь, это поможет.
Обычно такое случается, когда люди копируют cURL из любых прокси-инструментов, таких как Charles.
Как упоминалось в нескольких ответах выше, вы можете напрямую импортировать cURL в POSTMAN. Но если URL-адрес авторизован (или не работает по какой-либо причине), я предлагаю вам вручную добавить все точки данных в виде JSON в тело почтальона. возьмите URL-адрес API из cURL.
Заголовки: Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J где «cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS *** U056V25J» является закодированной формой «rzp_test_26ccbdbfe0e84b: 69b2e24411e384f91213f22a» `
небольшой совет: для кодирования вы можете легко перейти на свою хром-консоль (щелкнуть правой кнопкой мыши => проверить) и ввести: btoa(«string you want to encode») (или использовать базовую авторизацию почтальона)
👨💻 Практическое занятие «Используем методы при помощи curl»
Наш пример API прогноза погоды не позволяет использовать что-либо, кроме метода GET, поэтому для этого упражнения, чтобы использовать другие методы с curl, мы будем использовать API-интерфейс petstore. На самом деле мы не будем использовать интерфейс Swagger (о чем мы поговорим позже), на данный момент нам просто нужен API, с помощью которого мы можем создавать, обновлять и удалять контент.
В этом разделе мы создадим нового питомца с помощью Petstore API, обновим его, получим id питомца, удалим его, а затем попытаемся получить удаленного питомца.
Создание питомца
Для создания своего питомца, мы должны передать сообщение в формате JSON в теле запроса. Вместо того, чтобы пытаться кодировать JSON и передавать его в URL, мы сохраним JSON в файле и будем ссылаться на него.
Меняем значение в первом id и поменяем кличку с fluffy на какое-нибудь другое
В Терминале /командной строке переходим в каталог с сохраненным файлом.
Для перехода по каталогам:
После того, как вы перешли в Терминале/командной строке в каталог с сохраненным JSON файлом, создаем нашего питомца следующим curl запросом:
Content-Type указывает тип контента, представленного в теле запроса. Accept указывает тип контента, который мы примем в ответе.
Ответ будет выглядеть примерно так:
Проверьте, что в ответе кличка именно вашего питомца.
Обновление питомца
А что если питомец не любит свое имя?
Изменим ему имя на другое используя метод обновления.
Вместо метода POST используем метод PUT для обновления имени (в остальном запрос не меняется):
В ответе будет новое имя питомца.
Получение имени питомца при помощи ID
Теперь узнаем имя питомца, передав его ID в конечную точку /pet/
В команде curl заменим 51231236 на id своего питомца и узнаем информацию о нем:
В ответе будет информация о нашем питомце:
Можно отформатировать JSON, вставив его в инструмент форматирования JSON
Удаление питомца
“Извини, сынок, собака была бешеной, пришлось пристрелить” (© “Маска” фильм, 1994)
Для удаления питомца используем метод DELETE. В примере ниже меняем 5123123 на id своего питомца:
Теперь проверим, получилось удалить питомца. Используем метод GET в этой же команде
Ответ будет примерно таким:
Этот пример позволил нам увидеть, как можно работать с curl для создания, чтения, обновления и удаления ресурсов. Эти четыре операции называются CRUD и являются общими почти для каждого языка программирования.
Хотя Postman, вероятно, проще в использовании, curl используется на уровне мощности. Команды тестирования часто создают сложные тестовые сценарии, которые повторяют множество запросов curl.
Импорт curl в Postman
Можно импортировать команды curl в Postman выполняя следующее:
Открываем новую вкладку в Postman и нажимаем Import в левом верхнем углу.
В диалоговом окне выбираем вкладку “Paste Raw Text” и вводим команду:
Указываем свой Id питомца и проверяем, что нет лишних пробелов.
Нажимаем на кнопку Import
Закрываем диалоговое окно, если не закрылось автоматически.
Нажимаем кнопку Send (Если питомец был удален, то будет выдана ошибка “Pet not found”)
Экспорт Postman в curl
Можно экспортировать Postman в curl, выполнив следующие действия:
Благодаря функциям импорта и кода Postman можно легко переключаться между Postman и curl.
Activity: Use methods with curl
Our sample weather API doesn’t allow you to use anything but a GET method, so for this exercise, to use other methods with curl, we’ll use the petstore API from Swagger. However, we won’t actually use the Swagger UI (which is something we’ll explore later). For now, we just need an API with which we can use to create, update, and delete content.
In this example, using the Petstore API, you’ll create a new pet, update the pet, get the pet’s ID, delete the pet, and then try to get the deleted pet.
Create a new pet
To create a pet, you have to pass a JSON message in the request body. Rather than trying to encode the JSON and pass it in the URL, you’ll store the JSON in a file and reference the file.
A lot of APIs require you to post requests containing JSON messages in the body. Request bodies are often how you configure a service. The list of JSON key-value pairs that the API accepts is called the “Model” in the Swagger UI display.
Change the first id value to another integer (a whole number in this case). Also, change the pet’s name of fluffy to something else.
Use a unique ID and name that others aren’t likely to also use. Also, don’t begin your ID with the number 0.
In your terminal, browse to the directory where you saved the mypet.json file. (Usually, the default directory is Users/YOURUSERNAME — hence the previous step.)
If you’ve never browsed directories using the command line, here’s how you do it:
After your terminal or command prompt is in the same directory as your JSON file, create the new pet with the following curl request:
The Content-Type indicates the type of content submitted in the request body. The Accept indicates the type of content we will accept in the response.
The response should look something like this:
In the response, check to see that your pet’s name was returned.
Update your pet
Guess what, your pet hates its name! Change your pet’s name to something more formal using the update pet method.
Use the PUT method instead of POST to update the pet’s name (keep the same curl content otherwise):
Get your pet’s name by ID
Find your pet’s name by passing the ID into the /pet/
Use this curl command to get information about that pet ID, replacing 51231236 with your pet ID.
The response contains your pet’s name and other information:
You can format the JSON by pasting it into a JSON formatting tool:
Delete your pet
Unfortunately, your pet has died. It’s time to delete your pet from the pet registry.
Use the DELETE method to remove your pet. Replace 5123123 with your pet ID:
Now check to make sure your pet is removed. Use a GET request to look for your pet with that ID:
You should see this error message:
This example allowed you to see how you can work with curl to create, read, update, and delete resources. These four operations are referred to as CRUD and are common to almost every programming language.
Although Postman is probably easier to use, curl lends itself to power-level usage. Quality assurance teams often construct advanced test scenarios that iterate through a lot of curl requests.
Understanding idempotent methods
One concept important to understand with HTTP methods is “idempotency.” Roy Fielding defines idempotency as follows:
A request method is considered “idempotent” if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent” (RFC 7231, 4.2.2.
In other words, with idempotent methods, you can run them multiple times without multiplying the results. Idempotent methods include GET, PUT, and DELETE, while POST is not (see 8.1.3 for a more detailed list).
Todd Fredrich explains idempotency by comparing it to a pregnant cow. Let’s say you bring over a bull to get a cow pregnant. Even if the bull and cow mate multiple times, the result will be just one pregnancy, not a pregnancy for each mating session.
Import curl into Postman
You can import curl commands into Postman by doing the following:
Select Paste Raw Text and insert your curl command:
Make sure you don’t have any extra spaces at the beginning.
Export Postman to curl
You can also export Postman to curl by doing the following:
Click the Code button (it’s right below Save).
Copy the code snippet.
In place of APIKEY you should see your actual API key.
Insert the curl command into your terminal and observe the result.
Through Postman’s Import and Code functionality, you can easily switch between Postman and curl.
How to Make API Requests with Postman or cURL
A reference guide to making GET, POST, PUT, PATCH, and DELETE API calls through the command line via cURL and their Postman equivalents.
Postman is an API testing environment. cURL is a command line tool for transfering data via URLs. When it comes to REST APIs, we can use Postman as a GUI (graphical user interface) and cURL as a CLI (command line interface) to do the same tasks.
If you don’t yet understand REST or know how to use REST APIs, please read Understanding REST and REST APIs.
I’m going to use JSON Placeholder, an awesome example site for testing API calls. You can follow along and paste all the commands into your terminal to see what response you get.
Method | Endpoint |
---|---|
GET | https://jsonplaceholder.typicode.com/posts |
POST | https://jsonplaceholder.typicode.com/posts |
PUT | https://jsonplaceholder.typicode.com/posts/1 |
PATCH | https://jsonplaceholder.typicode.com/posts/1 |
DELETE | https://jsonplaceholder.typicode.com/posts/1 |
You can click those URLs to see the GET values they provide to the browser. You can use the browser for GET, but you’ll have to use cURL or Postman to POST, PUT, PATCH or DELETE.
cURL CLI arguments
Here are a few cURL argument we’ll pass with our requests. All requests will simply be curl followed by the argument and data to pass.
GET retrieves data.
All you have to do for Postman is paste the URL, select GET, and send.
POST creates a new resource. It is non-idempotent, meaning that two identical POST requests will create two new resources.
PUT updates an existing resource. It is idempotent, meaning that two identical PUT requests will modify the same resource. A PUT request requires the entire body to be sent through; if any data is missing, that data will be wiped (except automatic values like auto-incrementing IDs and timestamps).
Sending the values is the same as with POST.
PATCH updates an existing resource, and does not require sending the entire body with the request.
No change to sending the values.
DELETE removes a resource.
If you need to send additional headers, like Authorization: Bearer or x-jwt-assertion for JWT-based authentication, you can do it through cURL like this.
In Postman, you’ll go to Headers and add Authorization as the key and Bearer as the value to send authentication values. You can also go to Headers, click Presets, Manage Presets, and put your own reusable variables in for any headers or values you’ll be reusing a lot.
This guide provides all the basics for getting started with testing your APIs, either through Postman’s GUI or cURL’s CLI, using JSON or urlencoded form data.