restAssured - cannot master post method - java

fellow stackoverflowians :)
I've been for quit time to make a Post call using Gmail API.
Been trying to use createDraft and createLabel.
Now I guess I've found how to do this correctly (mostly) but I get this error:
java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <400>.
I realise that this error occurs because I make incorrect request.
Could You, guys, help me with this?
Here's my code:
import io.restassured.RestAssured.*
import io.restassured.http.ContentType
import io.restassured.matcher.RestAssuredMatchers.*
import org.hamcrest.Matchers.*
import org.testng.annotations.Test
class RestAPIAutoTestPost {
#Test
fun createLabelInGoogleMail() {
RestAssured.baseURI = "https://www.googleapis.com/gmail/v1/users/me"
val accessToken = "ya29.Glw7BEv6***"
val jsonAsMap = HashMap<String, Any>()
jsonAsMap.put("id", "labelAPITestNameID")
jsonAsMap.put("labelListVisibility", "labelShow")
jsonAsMap.put("messageListVisibility", "show")
jsonAsMap.put("messagesTotal", "0")
jsonAsMap.put("messagesUnread", "0")
jsonAsMap.put("name", "labelAPITestName")
jsonAsMap.put("threadsTotal", "0")
jsonAsMap.put("threadsUnread", "0")
jsonAsMap.put("type", "user")
given().
contentType(ContentType.JSON).
body(jsonAsMap).
`when`()
post("/labels?access_token=$accessToken").
then().
statusCode(200)
}
}
I suppose I use HashMap incorrectly or I use some incorrect body fields.
I've only started to learn restAssured so I beg my pardons for newby question.
Thanks!
P.S. I'd really appreciate for any help with Post methods and puting data into body

I think your use of RestAssured and HashMap is correct. I think you are getting a 400 from this API because you are specifying the id property. By playing with this in Google's API Explorer, I was able to generate 400 errors by doing that. According to the documentation, the only things you need to specify for a POST/Create are: labelListVisibility, messageListVisibility, and name. The id is returned to you as part of the response.
A good feature in RestAssured is that you can have it log what it sends or receives when there is an error or all the time.
Log all requests:
given().log().all()
Log all responses:
`when`().log().all()
Or just when validations fail:
`when`().log().ifValidationFails()
Using that will give you a more precise reason why your interaction with the API is failing because it will show whatever Google is sending back. So we can see for sure if I'm right about the id.
And since you seem to be using Kotlin for this, you might want to take advantage of its great multiline string capabilities and just create the JSON payload manually:
val body = """
{
"labelListVisibility": "labelShow",
"messageListVisibility": "show",
"name": "ThisIsATest"
}
"""

Related

Serenity screenplay rest extract value from response

I'm trying to extract class Header from response but can't find solution to that can please anyone guide me on this ?
Actor actor = Actor.named("ADMIN").whoCan(CallAnApi.at(baseUrl));
actor.attemptsTo(Get.resource("headers/" + rsplId).with(request -> request.header("Content-Type", "application/json")
.relaxedHTTPSValidation()
.cookies(cookies)));
actor.should(seeThatResponse(response -> response.assertThat().statusCode(200)
.extract().response().as(Header.class)
));
actor.should is void and when I tried to find anything inside seeThatResponse static method returning ReponseConsequence and see the message only thing I found inside was message that it was succesfull.
My method is returning Header but I don't know how to return this extracted Header inside response -> response.
I found solution with this approach maybe it'll help someone in the future.
actor.should(seeThatResponse(response -> response.assertThat().statusCode(200)));
return SerenityRest.lastResponse().as(Header.class);

POST request in postman got 307, unable to reproduce in restassured

I have a POST request, which I tried first in Postman, I wanted to capture the status code before it's redirected. In Postman, I got 307 (I set the settings so it doesn't follow redirects).
Postman
But when I tried using restassured, it still got redirected, so I got 200 status code instead of 307.
Tried the same way with GET request with 302 status code, and that one works.
public void postDataBeforeLogin() {
//post data before login
Response response = RestAssured.given().redirects().follow(false).post("/data");
assertEquals(response.getStatusCode(), 307);
}
I read an article/post about restassured not redirecting POST requests, but it was from 3 years ago, so I'm not sure if that is still the case.
Can anyone help/clarify?
Help will be greatly appreciated, thank you!
RestAssuredConfig will meet your requirements, like this:
given().config(RestAssured.config().redirect(redirectConfig().followRedirects(false))).
in your case:
import static io.restassured.config.RedirectConfig.redirectConfig;
Response response = RestAssured.given()
.config(RestAssured.config().redirect(redirectConfig().followRedirects(false)))
.post("/data");
See more: REST-assured wiki
It's recommended to statically import methods, see this

Retrofit, IGDB Api - How to correctly pass Api Key?

I'm trying to make an query on the internet game database (IGDB) Api using retrofit. In the past, when I used other Api, such as the movie database (TMDB), the api-keys were always passed in as a query, so the interface would look something like this.
#GET("/3/movie/popular")
Call<MovieResults> getPopularMovie(
#Query("api_key") String apiKey,
#Query("language") String language,
#Query("page") int page
);
But with IGDB, I think they want me to pass in the api-key as a Header (I'm not 100% sure, please correct me if I'm wrong). I've never passed an api-key through a header before, so with some guesswork, following is what my interface looks like.
#Headers({
"Accept: application/json",
"user-key: b5bd50####################8b2"
})
#GET("/games")
Call<List<Game>> getGame();
Problem is, when I make the call, although the call ends up in onResponse, the response.body is always null.
So, I ran the code in de-bug mode, and i found this message:
response = Response{protocol=http/1.1, code=401, message=Unauthorized, url=http://v2000.igdb.com/games/}
I don't know what this means, but I am guessing that it isn't recognizing an authorised api-key?
Another interesting anomaly is that, the base url I pass in is:
"https://api-2445582011268.apicast.io/"
I don't know how that ended up being:
http://v2000.igdb.com/
If anyone have any experience with IGDB, please give me some help, will really appreciate it.
I have used this api with JAVA and i can confirm that you should send the API key in the header, so what you have done looks to be correct.
The base url you are getting is also wrong, try using https://api-endpoint.igdb.com/, it is the recommended url.
I can also recommend you to try the api using Postman, it is an excellent tool for testing.
If you are using java you might want to try their java wrapper

Accessing the edit method from google play developer rest api

I successfully authenticated to google play developer rest api and I am getting also the refresh token but I can figure out how to make an edit requests.
I have method signature at the following link:
https://developers.google.com/android-publisher/api-ref/edits/insert
I added the following header
Authorization:{{token_type}} {{access_token}}
but i cant figure out where to put the package name:
POST https://www.googleapis.com/androidpublisher/v2/applications/packageName/edits
I putted packageName like above using get and also as post parameter and in both cases i am encountered "404 not found" error.
Please help.
You can try
POST https://www.googleapis.com/androidpublisher/v2/applications/edits?id = packageid && expiryTimeSeconds = 20
GET https://www.googleapis.com/androidpublisher/v2/applications/**packageName**/edits/**editId**
according to
https://developers.google.com/android-publisher/api-ref/edits#methods
Please verify if you have followed all steps for authentication and authorization as shown here.
Since you are not getting 401 or 403, you might be sending the token correctly.
To call the api:
put your package name as a path paramters and specify the edit resource in the body. Please note that the edit resource is ignored but needs to be provided.
send your request like this:
POST https://www.googleapis.com/androidpublisher/v2/applications/yourPackageNameHere/edits
in the body:
{
"id": "abcd",
"expiryTimeSeconds": "asd"
}
make sure u provide content type in header as well.
Authorization is also required in the headers as you mentioned.
Hope this helps. :)

How do I get Rest Assured to return the text (non-encrypted or streamed) value in my REST response?

I recently moved over to Java and am attempting to write some REST tests against the netflix REST service.
I'm having an issue in that my response using rest assured either wants to send a gzip encoded response or "InputStream", neither of which provide the actual XML text in the content of the response. I discovered the "Accept-Encoding" header yet making that blank doesn't seem to be the solution. With .Net I never had to mess with this and I can't seem to find the proper means of returning a human readable response.
My code:
RestAssured.baseURI = "http://api-public.netflix.com";
RestAssured.port = 80;
Response myResponse = given().header("Accept-Encoding", "").given().auth().oauth(consumerKey, consumerSecret, accessToken, secretToken).param("term", "star wars").get("/catalog/titles/autocomplete");
My response object has a "content" value with nothing but references to buffers, wrapped streams etc. Trying to get a ToString() of the response doesn't work. None of the examples I've seen seem to work in my case.
Any suggestions on what I'm doing wrong here?
This has worked for me:
given().config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders())).get(url)
I guess in Java land everything is returned as an input stream. Using a stream reader grabbed me the data I needed.
Until its version 1.9.0, Rest-assured has been providing by default in the requests the header "Accept-Encoding:gzip,deflate" with no way of changing it.
See
https://code.google.com/p/rest-assured/issues/detail?id=154
It works for me:
String responseJson = get("/languages/").asString();

Categories