- RESTful API Requests from Client to Server via Command Line
- What is curl?
- Install curl
- To check to see if you have curl installed on your computer:
- GET request with curl
- What is a GET request?
- Example of a GET request
- Breaking down the GET request
- Where is the type of request?
- Do more?
- POST request with curl
- What is POST request?
- Example of a POST request
- Breaking down the POST request
- Sending data in the request body
- Sending the type of request
- Server side
- Send JSON data in POST Request
- PUT request with curl
- What is PUT request?
- Example of a PUT request
- Breaking down the PUT request
- Server side
- Send JSON data in PUT Request
- PATCH request with curl
- What is PATCH request?
- Example of a PATCH request
- Breaking down the PATCH request
- Server side
- DELETE request with curl
- What is DELETE request?
- Example of a DELETE request
- Breaking down the DELETE request
- Server side
- Want to learn more? Get 200+ courses and 2,000 hours in the Mammoth Unlimited Membership.
- Как сделать POST-запрос с помощью cURL
- Выполнение запроса POST
- Указание Content-Type
- Загрузка файлов
- Выводы
RESTful API Requests from Client to Server via Command Line
Want to learn more? Get 250+ courses and 2,000 hours in the Mammoth Unlimited Membership.
What is curl?
curl is a tool to transfer data from or to a server
Install curl
To check to see if you have curl installed on your computer:
- Open your Terminal application (also called Command Line or Command Prompt)
- Enter the command: curl
- If you see, “Error: curl not found,” install curl.
GET request with curl
What is a GET request?
This type of HTTP request is for retrieving data.
Example of a GET request
Paste the following code into your Terminal (or Command Line) application to make a GET request from http://localhost:3000/api:
curl http://localhost:3000/api
Breaking down the GET request
- curl is the command to use the curl tool
- http://localhost:3000/api is the route from which you want to get data. You must replace this with whichever route your project uses to handle a GET request.
Your sever must listen for the client’s request of http://localhost:3000/api. The server’s response must be to display all the data in the database.
Note – Your server must handle each route that you visit, such as http://localhost:3000/api.
Where is the type of request?
The default HTTP request type is GET. Therefore, we don’t have to specify the type of request in the command.
Do more?
You can also use GET to retrieve one piece of data by an identifier, like a unique ID.
POST request with curl
What is POST request?
This type of HTTP request is for creating a new entry in a database.
Example of a POST request
curl -d “name=Alex&course=Unreal” -X POST http://localhost:3000/api/people
Breaking down the POST request
Sending data in the request body
- -d is the command to specify that the next code will be data (the body of your request).
- We need to send data containing the properties of the object we want to add to our database.
- 1 property of the object is name, which has the value Alex.
- Another property of the object is course, which has the value Unreal.
- Properties are separated with an ampersand (‘and’ symbol) &.
Sending the type of request
- -X is the command to specify that the next code will be the type of request sent.
- POST is the type of request we are sending, a POST HTTP request.
- http://localhost:3000/api/people is the route that handles posting data.
Server side
- Note – Your sever must listen for the client’s POST request of http://localhost:3000/api/people.
- The server’s response must be to take the data in the body of the request and put it into the project database.
Send JSON data in POST Request
curl -d '' -H "Content-Type: application/json" -X POST http://localhost:42212/products
- The property names can have any capitalization.
- Strings will be converted to integers if required.
- If your Terminal does not allow single quotes, you have to escape out of inner double quotes with a backslash.
PUT request with curl
What is PUT request?
This type of HTTP request is for updating an entry entirely in the database.
Example of a PUT request
curl -d “name=Alex&course=Excel” -X PUT http://localhost:3000/api/people/61326891216b79d8768c6edd
Breaking down the PUT request
- curl is the command to use the curl tool
- -d is the command to specify that the next code will be data (the body of your request).
- We need to send data containing the properties of the object we want to add to our database.
- 1 property of the object is name, which has the value John.
- Another property of the object is course, which has the value Excel.
- Properties are separated with an ampersand (‘and’ symbol) &.
- You must replace :id with an actual id of an entry in your database, such as 61326891216b79d8768c6edd.
- An ID is a unique identifier for each entry in your database.
- The ID value is known as a parameter of the request.
Server side
- Note – Your sever must listen for the client’s PUT request at http://localhost:3000/api/people/:id.
- The server must take in the parameter of the request, the ID, and find an entry in the database at that ID.
- If no entry exists, throw an error.
- Replace the old name and course Alex and Unreal with John and Excel.
Send JSON data in PUT Request
curl -d '' -H "Content-Type: application/json" -X PUT http://localhost:42212/products/2
PATCH request with curl
What is PATCH request?
This type of HTTP request is for updating 1 property of an entry in the database.
Example of a PATCH request
curl -d name=Mammoth -X PATCH http://localhost:3000/api/people/61326891216b79d8768c6edd
Breaking down the PATCH request
- curl is the command to use the curl tool
- -d is the command to specify that the next code will be data (the body of your request).
- We need to send data containing the properties of the object we want to add to our database.
- You must replace :id with an actual id of an entry in your database, such as 61326891216b79d8768c6edd.
- An ID is a unique identifier for each entry in your database.
- The ID value is known as a parameter of the request.
Server side
- Note – Your sever must listen for the client’s PATCH request at http://localhost:3000/api/people/:id.
- The server must take in the parameter of the request, the ID, and find an entry in the database at that ID.
- If no entry exists, throw an error.
- Replace the old name John with the new name Mammoth.
DELETE request with curl
What is DELETE request?
This type of HTTP request is for deleting an entry in a database.
Example of a DELETE request
curl -X DELETE http://localhost:3000/api/people/61325f4594bd88dec1e165cb
Breaking down the DELETE request
- curl is the command to use the curl tool
- -X is the command to specify that the next code will be the type of request sent.
- DELETE is the type of request we are sending, an HTTP DELETE request.
- http://localhost:3000/api/people/:id is the route that handles deleting data.
- You must replace :id with an actual id of an entry in your database, such as 61326891216b79d8768c6edd.
- An ID is a unique identifier for each entry in your database.
- The ID value is known as a parameter of the request.
Server side
- Note – Your sever must listen for the client’s DELETE request at http://localhost:3000/api/people/:id.
- The server must take in the parameter of the request, the ID, and find an entry in the database at that ID.
- If no entry exists, throw an error.
Want to learn more? Get 200+ courses and 2,000 hours in the Mammoth Unlimited Membership.
Как сделать 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 .
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.