Lesson 020 – POSTing to a REST API


Back in Lesson 015, we took a look at what you need to do in order to make HTTP Requests against a REST API. In that example, we only made a GET request, which limited us to a “read-only” interaction with a server. In the real world, we would need to send data back to the server. Whether that is to log in, save a picture to an online album, or post a status update, we are going to move beyond “read-only” pretty quickly.

Good News

The good news is that we can leverage almost everything that we did back in Lesson 015. Today, we’ll be using a free tester REST API located at http://reqres.in/. When you POST to http://reqres.in/api/users, it will add an id and timestamp field and just echo back any data you posted to it. So, let’s take a look at how we POST.

There are a few differences right off the bat. First, we added these lines

The first line just sets the code to make the request as a POST instead of a GET. GET is the default, which is why we didn’t specify this previously. Next, declare a body for our request. Whenever you submit a form on a normal website, that data will often be transmitted in exactly the format you see here. We have a key=value syntax with ampersands (&) separating each term. Next we encode that string so it can be understood and assign it to the body of the request.

After that, everything is exactly the same, with the exception that I’m pulling different keys out of the resulting JSON array. That should make sense, given that we are hitting a different endpoint. Remember that this code is all on GitHub, so you can absolutely pull it down. Add values to the body and then try to pull them back out again. Get familiar with how this “song and dance” goes. For example, when I make this request, I get the following result

A Few Closing Notes

Even if you run my exact code, you will get a different id every time you request. That seems to be random. Also, whenever I run this in the playground, I always get these errors first, which do not seem to affect whether the code executes properly. I didn’t get a lot of help when I Googled it, and it seemed to be harmless, so I’m ignoring it.

Add Comment

Required fields are marked *. Your email address will not be published.