cURL Tips: Making Post Requests

Image for post
Image for post
Photo by Alex Korolkoff on Unsplash

Introduction

What is cURL?

For this tips blog post, I wanted to discuss using cURL to make POST requests and I will show you two ways you can go about doing that.

Post Request with a Body

curl -X POST -d "<param1>=<value1>&<param2>=<value2>"

However, you should note that when sending your requests this way, the default content-type is application/x-www-form-urlencoded . So if you want to work with JSON specifically, you will need to change that. We can do this by using the headers symbol or -H in our request.

We can change it to application/json like this:

-H “Content-Type: application/json”

I’ll show you an example using the free API resource JSONPlaceholder:

curl -X POST -H “Content-Type: application/json” -d ‘{“title”:”hello”, “body”:”test”, “userId”:2}’ https://jsonplaceholder.typicode.com/posts *

*make sure to wrap the object in single quotes.

This is what is returned:

There are 100 total comments in the API before we make our post and we know that our request is successful because:

  1. We do not get an error message in the terminal(and as I like to say, “no error message is a good message.”)
  2. The id is now 101 which was not one of our parameters but one the “database” will assign upon successful posting, letting us know the new total of comments is 101.

A way to also verify a successful post is to check the head of the request. You can add on -i to the cURL request like so:

curl -X POST -H “Content-Type: application/json” -d ‘{“title”:”hello”, body”:”test”, “userId”:2}’ https://jsonplaceholder.typicode.com/posts -i

and you will see this information like this:

HTTP/2 201
date: Fri, 18 Dec 2020 23:20:17 GMT
content-type: application/json; charset=utf-8
content-length: 68...

We can see it has a status code of 201.

Post Request with a File

Here is an example again with the JSONPlaceholder API:

Here is the test1.json

Here is the cURL request:

curl -X POST -H “Content-Type: application/json” -d ‘@test1.json’ https://jsonplaceholder.typicode.com/posts

With our response returned below.

{
“userId”: 2,
“title”: “This is a second through a file upload”,
“body”: “This is the second body”,
“id”: 101
}

Conclusion

Software Developer && Political Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store