Automation Testing

REST-ASSURED – HOW TO POST A JSON REQUEST

By Test Guild
  • Share:
Join the Guild for FREE

In my last few posts we went over getting started with rest-assured and how to get request using the new given, when, then syntax — now that we have some get request method examples under our belt I wanted to take a look at a few examples of using Rest-Assured to test JSON REST services using the POST method.

Setup – CouchDB

To make this example as easy as possible and not have to setup any sort of authentication, I'll use Apache couchDB. CouchDB is easy to install, stores data as JSON documents and has an easy-to-use API to interact with it. This makes it a great application to use to teach us more about REST testing rest-assured and JSON.

To install couchDB go to:

  1. http://couchdb.apache.org/
  2. Click on Download and choose the version you want to us
  3. Once it's installed, enter http://127.0.0.1:5984/_utils/ in a browser. This should bring up your local CouchDB Futton web site.
  4. Next, click on the Create Database and name it “restassured”



  1. Navigate back to http://127.0.0.1:5984/_utils/index.html. Notice that restassured shows 0 docs.


You can also check out my SoapUI – How to Post Json to a Rest Service video for how to install couchDB.

Time to use Rest-Assured to Send a Post Request


For some reason, I had a hard time figuring out how to do this. Whatever the reason, I finally got it to work. Remember — I’m still learning this myself, and posting what I’m learning along the way. There may be better way of doing it, but for now I’m sharing what worked for me to hopefully help get you started if you’re also struggling to get the POST to work.

  • In your IDE, create a new java class named CouchDB_REST
  • Import the following:
import org.junit.Test;
import org.junit.Before;
import static com.jayway.restassured.RestAssured.expect;
import static org.hamcrest.Matchers.equalTo;
  • Create a public method named postExample
  • Add the junit @Test annotation above it.
        @Test
 public void postExample()
 {
 String myJson = "{\"name\":\"Jimi Hendrix\"}";
     RestAssured.baseURI  = "http://127.0.0.1:5984/restassured"; 

     Response r = given()
     .contentType("application/json").
     body("{\"name\":\"Jimi Hendrix\"}").
        when().
        post("");

     String body = r.getBody().asString();
     System.out.println(body);

 }
  • Right click on the CouchDB_REST.java and Run As>Junit Test
  • Your test should pass

  • Look for the id in the Console output:

  • Go back to couchDB: http://127.0.0.1:5984/_utils/index.html
  • Notice how your restassured now shows Number of Documents 1
  • Click on the restassured db link and notice how the ID under the key column matches the id returned in the java console

More Rest-Assured Post

REST-ASSURED – HOW TO POST A JSON REQUEST

REST-assured How to Check Response Times

REST Testing with Java Part Two: Getting Started with Rest-Assured

 

A bearded man with blue glasses and a black-and-white jacket smiles at a microphone in a studio setting.

About Joe Colantonio

Joe Colantonio is the founder of TestGuild, an industry-leading platform for automation testing and software testing tools. With over 25 years of hands-on experience, he has worked with top enterprise companies, helped develop early test automation tools and frameworks, and runs the largest online automation testing conference, Automation Guild.

Joe is also the author of Automation Awesomeness: 260 Actionable Affirmations To Improve Your QA & Automation Testing Skills and the host of the TestGuild podcast, which he has released weekly since 2014, making it the longest-running podcast dedicated to automation testing. Over the years, he has interviewed top thought leaders in DevOps, AI-driven test automation, and software quality, shaping the conversation in the industry.

With a reach of over 400,000 across his YouTube channel, LinkedIn, email list, and other social channels, Joe’s insights impact thousands of testers and engineers worldwide.

He has worked with some of the top companies in software testing and automation, including Tricentis, Keysight, Applitools, and BrowserStack, as sponsors and partners, helping them connect with the right audience in the automation testing space.

Follow him on LinkedIn or check out more at TestGuild.com.

  1. Hi Joe
    Thanks for the great explanation

    I do have some questions though!
    How do you got your myJSON string?
    My Json code is huge and am unware how to format it to string
    Here goes my JSON Code:

    {“GuestOrder”:{“GuestOrderNumber”:”999456789″,”GuestFirstName”:”Abraham”,”GuestLastName”:”Doe”,”OriginatorCode”:”OMS”,”FulfillmentLocation”:”3303″,”EventDateTime”:”2012-12-10T11:10:20″,”MessageDateTime”:”2012-12-10T11:10:22″,”PriorityCode”:”storepickup”,”FulfillByDateTime”:”2012-12-10T11:11:22″,”StoreTransferOrderList”:{“StoreTransferOrder”:”101220009100″,”StoreTransferShipmentList”:{“StoreTransferShipment”:”8822700100″,”ReleaseNumber”:”98591069710444″,”ContainerList”:{“Container”:[{“ContainerNumber”:”9876544001″,”TrackingNumber”:”1Z123AB45CD6789001″,”ItemList”:{“Item”:{“TCIN”:”991238822″,”LineNumber”:”1″,”ShipmentLineNumber”:”1″,”Dept”:”123″,”Class”:”12″,”Item”:”1234″,”RequestedQTY”:”12″,”Notes”:”First Container First Item “}}},{“ContainerNumber”:”9876555200″,”TrackingNumber”:”1ZA819CD412L569200″,”ItemList”:{“Item”:[{“TCIN”:”119998888″,”LineNumber”:”2″,”ShipmentLineNumber”:”2″,”Dept”:”123″,”Class”:”12″,”Item”:”1234″,”RequestedQTY”:”12″,”Notes”:”second Container First Item “},{“TCIN”:”229998888″,”LineNumber”:”1″,”ShipmentLineNumber”:”3″,”Dept”:”9″,”Class”:”12″,”Item”:”99″,”RequestedQTY”:”12″,”Notes”:”second Container second Item “}]}}]}}}}}

  2. i have a payload similar to

    {
    “createdBy”: “exchange@sdp.com”,
    “createdOn”: “2015-08-07T16:47:27.527+05:30”,
    “id”: 500050,
    “updatedBy”: “exchange@sdp.com”,
    “updatedOn”: “2015-08-11T12:35:29.606+05:30”,
    “accountContexts”: [
    “EXCHANGE”
    ],
    “accountReferenceId”: “C00000003”,
    “billPayer”: false,
    “changePassword”: false,
    “correspondenceAddress”: {
    “createdBy”: “exchange@sdp.com”,
    “createdOn”: “2015-08-07T16:47:27.528+05:30”,
    “id”: 500050,
    “updatedBy”: “exchange@sdp.com”,
    “updatedOn”: “2015-08-07T16:47:27.528+05:30”,
    “city”: “bangalore”,
    “country”: “india”,
    “postalCode”: “23167”,
    “state”: “KA”,
    “street”: “Sarjapur”
    },
    “emailAddress”: “operator111@cim.com”,
    “name”: “operator111@cim.com”,
    “parentInfo”: {
    “createdBy”: “superadmin”,
    “createdOn”: “2015-05-13T12:41:23.433+05:30”,
    “id”: 1011,
    “updatedBy”: “superadmin”,
    “updatedOn”: “2015-05-13T12:41:23.433+05:30”,
    “accountContexts”: [
    “EXCHANGE”
    ],
    “accountReferenceId”: “A1011”,
    “billPayer”: true,
    “emailAddress”: “exchange@sdp.com”,
    “name”: “EXCHANGE”,
    “phoneNumber”: “9181818181”,
    “representative”: false,
    “state”: “ACTIVE”,
    “typeId”: 1001,
    “typeName”: “EXCHANGE_ACCOUNT_TYPE”,
    “userName”: “exchange@sdp.com”
    },
    “phoneNumber”: “234567”,
    “representative”: false,
    “state”: “OBSOLETE”,
    “type”: {
    “createdBy”: “exchange@sdp.com”,
    “createdOn”: “2015-08-07T12:53:04.048+05:30”,
    “id”: 500000,
    “updatedBy”: “exchange@sdp.com”,
    “updatedOn”: “2015-08-07T12:53:04.048+05:30”,
    “name”: “CIM_USERS”,
    “ownerName”: “EXCHANGE”
    },
    “useExternalAuthentication”: false,
    “userName”: “operator111@cim.com”,
    “password”: “Cisco_123”
    }

    could you please help me how to send above payload as post request.

  3. Hi,
    With respect to the questions posted by Balveer and QA Tester,
    you may want to create a class with all the required fields, instatiate it and then pass the object in the body.
    Say from Balveer’s payload above, userName, accountReferenceID, updatedBy etc will constitute the fields, include getters and setters in the class for the fields, instantiate the class with an Object say payload_obj and pass it as an Object within the body.

    body(payload_obj).

  4. Add your file in the resource folder and call it using below code ..
    URL file = Resources.getResource(“yourfile.json”);
    String myJson = Resources.toString(file, Charsets.UTF_8);

    Response responsedata = given().header(“Authorization”, AuthrztionValue)
    .header(“X-App-Client-Id”, XappClintIDvalue).contentType(“application/vnd.api+json”).body(myJson).with()

    .when().post(your URL)

Comments are closed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Why Enterprise Test Automation is Broken—And How to Fix It

Posted on 03/21/2025

Why is Enterprise Test Automation So Hard? Enterprise software testing should accelerate releases, ...

Exploring the Value of AI in Test Case Creation (Pros and Cons)

Posted on 03/10/2025

As testers, we're used to balancing test coverage with tight project deadlines. Right? ...

Solving the Top 6 Mobile Automation Challenges Fast (DevAssure Guide)

Posted on 02/27/2025

Are you tired of struggling with the mobile test automation setups? Does managing ...