Google API Crux API - Invalid JSON payload received. Unknown name "collectionPeriod": Cannot find field.' - google-api

I'm trying to set a date range using collectionPeriod for the google Crux API (https://developer.chrome.com/docs/crux/api/)
url = "https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=key"
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
data = {"origin":"https://www.example1.com",
"metrics": ["largest_contentful_paint", "experimental_time_to_first_byte"],
"collectionPeriod": {
"firstDate": {
"year": 2022,
"month": 10,
"day": 12},
"lastDate": {
"year": 2022,
"month": 11,
"day": 1}}
}
response = requests.post(url, json=data, headers=headers)
print(response.json())
However when I try the above I see the error:
{'error': {'code': 400, 'message': 'Invalid JSON payload received.
Unknown name "collectionPeriod": Cannot find field.', 'status':
'INVALID_ARGUMENT', 'details': [{'#type':
'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations':
[{'description': 'Invalid JSON payload received. Unknown name
"collectionPeriod": Cannot find field.'}]}]}}

Related

validate response using jsr223 assertion

I have passed chgId as parameter in the get HTTP request.
https://*****?chgId=405
My api response is coming as -
{
"response": {
"data": [
{
"tid": 3697,
"chgId": 405,
"amount": 8.5,
"Currency": "USD",
},
{
"tid": 3698,
"chgId": 405,
"amount": 3.33,
"Currency": "USD",
}
]
}
}
Now from the response I want to validate in JSR223 assertion that the response is correct based on the chgId field. That means in both 'data' array "chgId": 405 text should come.
Can anyone suggest?
You could do something like:
def params = org.apache.http.client.utils.URLEncodedUtils.parse(prev.getURL().toURI(), 'UTF-8')
def expected = params.find { 'chgId' }.value as int
def actual1 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[0].chgId
def actual2 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[1].chgId
def success = (expected == actual1 && expected == actual2)
if (!success) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('chgId mismatch')
}
where prev stands for previous SampleResult
More information:
URLEncodedUtils JavaDoc
JsonSlurper
Apache Groovy - Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

Swagger UI not rendering the correct response(Should return a JSON response)[This is for the GET request Code 200]

Swagger UI is not returning the expected JSON response in the example value. It is returning a empty list.Below are the code snippets I am using,
Gradle Dependency
compile('io.springfox:springfox-swagger-ui:2.9.2')
compile('io.springfox:springfox-swagger2:2.9.2')
Swagger Config
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(HttpServletResponse.class)
.select() .apis(RequestHandlerSelectors.basePackage("com.core.controller.v2"))
.paths(PathSelectors.any())
.build()
.enable(true)
.apiInfo(apiInfo())
.securityContexts(Lists.newArrayList(securityContext()))
.securitySchemes(Lists.newArrayList(apiKey()));
Controller
#ApiOperation(value="A GET request to get a list of all contents for a given user.",
notes = "This API is used to get the contents for a given user with an NPI and Partner ID",
response = CoreContentItem.class)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Success response", response = CoreContentItem.class,responseContainer = "List"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 400, message = "Bad Request",responseContainer = "String"),
#ApiResponse(code = 403, message = "Forbidden"),
#ApiResponse(code = 500, message = "Internal Server Error, please contact system administrator")})
Swagger Output
Swagger UI for success Response
Expected JSON response
This is a sample expected JSON response
[
{
"item": {
"id": "3f94ea1a687dda4af3e2",
"category": null,
"type": "EXTERNAL",
"headline": "DO NOT DELETE - REST ASSURED All - HIGH - JV",
"summary": "DO NOT DELETE - All - HIGH - JV",
"details": null,
"mediaURL": "",
"createdOn": 1493658088000,
"modifiedOn": 1495553312000,
"priority": "HIGH",
"startDate": 1493618400000,
"endDate": 1588312800000,
"feedbackEmail": null,
"totalLikes": 0,
"totalViews": 2,
"customData": null,
"userInteraction": {
"userLiked": false,
"userDisliked": false,
"userViewed": false
},
"availableActions": [
"View",
"Done",
"Submit"
],
"externalURL": "https://www.1234.com/vegetables/armando%25e2%2580%2599s-chiles-rellenos/r/5014"
}
}
]
I found the issue. Apparently it was a model mapping exception that made the Swagger UI to return an empty list. Now I am able to see the model in example value.
enter image description here

Swagger validation for request parameter and custom error message

I need a help regarding swagger validation with spring boot.
In Req1 it is not showing the field name, could you help with this? Also how to give custom error message for any validations?
Update:
In the response of the req1 is not showing field name(productCode) in message but in response of req2 we could see the field name.
type: object
description: get details request object
required: [productCode]
properties:
productCode:
type: string
minLength: 1
description: Identifier for application
--Req1-----
{
"productCode":""
}
--Res1-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: string \"\" is too short (length: 0, required minimum: 1)"
}
--Req2-----
{ }
--Res2-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: object has missing required properties ([\"productCode\"])"
}

Laravel 5.1 Date_Format Validator Fails on Y-m-d Format

I'm starting to use Request objects to validate incoming post data, and I've seen examples of how others are using date_format, but I can't seem to get dates to pass even though I'm using a format that passes when you use PHP's date_parse_from_format:
print_r(date_parse_from_format('Y-m-d','2015-07-27'));
Output
UPDATE: their is a warning in date_parse_from_format, but I don't understand why as it reflects the format.
{
"year": 2015,
"month": 2,
"day": 30,
"hour": false,
"minute": false,
"second": false,
"fraction": false,
"warning_count": 1,
"warnings": {
"10": "The parsed date was invalid"
},
"error_count": 0,
"errors": [],
"is_localtime": false
}
Validator
public function rules()
{
return [
'rental_id' => 'required|exists:rentals,id',
'start_at' => 'required|date_format:Y-m-d',
'end_at' => 'required|date_format:Y-m-d'
];
}
Using PostMan I'm sending in a payload of:
rental_id = 1 as text
start_at = 2015-02-30 as text
end_at = 2015-02-30 as text
And it throws a NotFoundHttpException, but if I comment out start_at and end_at in the validator request it passes, and enters my controllers action with the proper payload:
{
"rental_id": "1",
"start_at": "2015-02-30",
"end_at": "2015-02-30"
}
Apparently, the date_format validation failed as I randomly chose 2015-02-30 to test my API, but that day doesn't exist as that would be February 30... oh the shame and the wasted time. Thanks to #ceejayoz for all the help!!!

multiple responses for a given endpoint in api blueprint

Is it possible in the API Blueprint to define a set of possible responses for a given endpoint?
For example if I have a endpoint such as /movie/{id} I'd like to be able to define a set of movie records so that in the mock server I could GET /movie/1 or GET /movie/2 or GET /movie/3 and get the relevant record.
The examples I've seen all seem to define just one possible response.
You can add multiple request blocks, like this:
### Register [POST]
Registers an account
+ Request Already existing username
+ Body
{
"app": 3,
"username": "already-existing-username",
"password": "password"
}
+ Response 200 (application/json)
+ Body
{
"success": false,
"error": "The username specified is already registered to an account.",
"error_field": "username"
}
+ Request Invalid password
+ Body
{
"app": 3,
"username": "username",
"password": "password"
}
+ Response 200 (application/json)
+ Body
{
"success": false,
"error": "Please supply a valid password.",
"error_field": "password"
}
You can also find this in the official documentation
It's not possible to simulate this using a single action, but there is a workaround.
FORMAT: 1A
# Multi
## GET /movie/1
+ Response 200 (application/json)
{ "id": 1, "title": "First" }
## GET /movie/2
+ Response 200 (application/json)
{ "id": 2, "title": "Second" }
## GET /movie/3
+ Response 200 (application/json)
{ "id": 3, "title": "Third" }
## GET /movie/{id}
+ Parameters
+ id (required, number, `42`) ... Blah.
+ Response 200 (application/json)
{ "id": 42, "title": "First" }
Now, if you hit /movie/2, the mock server sends the appropriate response. Thanks.
this is how you provide multiple responses in your RAML file using Mulesoft(API designer) however if you're using mocking service for testing you'll always get the example response you set for testing
/{id}:
get:
headers:
Requester-Id:
required: true
responses:
200:
body:
application/json:
type: Account
example:
!include exapmle/AccountExample.raml
400:
body:
application/json:
example:
{"message":"Error retrieving account for the provided id"}

Resources