How to generate a Swagger #definition from sample JSON - json

Take the following #definition from the pet store example. Given a #definition section a JSON structure can be generated
e.g.
Is there something that can do the reverse given a largeish complex JSON file?
Given the below JSON Structure can I get the #defintion section of a swagger file generated to save some typing
{
"variable": "sample",
"object1": {
"obj-field1": "field 1 of object",
"obj-field2": "field 2 of object",
"anArray": [
"Value 1",
{
"anArrayObj1": "obj1fieldinarray",
"anArrayObj2": "obj2fieldinarray"
}
]
}
}

You can use this JSON-to-OpenAPI schema converter:
https://roger13.github.io/SwagDefGen/
(GitHub project)
I haven't used it personally though, so I'm not sure how good it is.
Since OpenAPI uses a subset of JSON Schema, you could also use one of the JSON Schema generators, however you may need to manually tweak the generated definition to make it OpenAPI-compatible.

1 - Paste a response in http://www.mocky.io and get a link to your response
2 - Go to https://inspector.swagger.io/ and make a call to your example response
3 - Select the call from "History" and click "Create API definition"
4 - The swagger definition will be available at https://app.swaggerhub.com/

You can use mock-to-openapi cli tool that generates OpenAPI YAML files from JSON mock.
npm install --global mock-to-openapi
then run the conversion of all *.json files from the folder:
mock-to-openapi ./folder/*.json`
Let's have, for example, json object with:
{
"title": "This is title",
"author": "Roman Ožana",
"content" : "This is just an example",
"date": "2020-05-12T23:50:21.817Z"
}
Tool mock-to-openapi converts JSON to the OpenAPI specification as follows:
type: object
properties:
title:
type: string
example: This is title
author:
type: string
example: Roman Ožana
content:
type: string
example: This is just an example
date:
type: string
format: date-time
example: 2020-05-12T23:50:21.817Z

This works for me:
Generate Swagger REST-client code (and POJO) from sample JSON:
Go to apistudio.io:
Insert -> New Model.
CutNpaste your JSON.
[The Swagger YML file will be generated]
Download -> YAML.
Go to editor.swagger.io:
CutNpaste the YML saved from last step.
Generate Client -> jaxrs-cxf-client (there are many other options).

Related

How Do I Structure This JSON CloudFormation Template

From this article, it shows how to deploy a AWS::Serverless::Function as a 'proxy' to do routing, a/b testing, etc.
The example template is in YAML, but we need to use JSON as that is what the AWS dotnet templates are built on.
There is a line in the YAML that I cannot figure out how to translate to a JSON template:
LambdaFunctionARN: !Ref LambdaEdgeFunctionSample.Version
In a JSON template a Ref just refers to another resource or parameter. You cannot Ref to a Resource.Property. For that you use Fn::GetAtt.
I have tried Fn::GetAtt, but that errors with "Version is an unknown attribute for this resource" (in the editor) and Template error: every Fn::GetAtt object requires two non-empty parameters, the resource name and the resource attribute during deployment:
"LambdaFunctionARN":{"Fn::GetAtt":["LambdaEdgeFunctionSample","Version"]}}
Mind you, these are both using AWS::Serverless::Function underneath, so there's more transforming going on.
Specifically, when the JSON template is transformed, it does create:
"LambdaEdgeFunctionSampleVersion1cfc342538": {
"Type": "AWS::Lambda::Version",
"DeletionPolicy": "Retain",
"Properties": {
"FunctionName": {
"Ref": "LambdaEdgeFunctionSample"
}
}
},
But I cannot use LambdaEdgeFunctionSampleVersion1cfc342538 as clearly that is a transient id.
How can I accomplish the same as the YAML template in a JSON template?
Apparently, AWS SAM does a transformation on !Ref LambdaEdgeFunctionSample.Version before the template is actually processed.
So, in Json, it's the same and SAM does the transformation:
{"Ref":"LambdaEdgeFunctionSample.Version"}
transforms to
{
"Ref": "LambdaEdgeFunctionSampleVersionf76b18e3ba"
}

How to send multiple JSON data from CSV file in single HTTP request in JMETER tool

my JSON structure is:
{
"ID": "1",
"DATE": "2",
"VILLA": [{
"HSENO":"${HSENO}",
"STREETNO": "${STREETNO}",
"CITY": "${CITY}",
"STATE": "${STATE}",
}],
"FLATS": []
}
My Excel Have 1000 datas (1000 HSENO, 1000 STREETNO, 1000 CITY, 1000 STATE) for Villa's.
In Jmeter how can I read these 1000 datas & make HTTP SINGLE request.
I have referred beanshell script but still couldn't succeed.
PLease help me. Thanks
Assuming that you have test.csv file in "bin" folder of your JMeter installation which looks like:
house1,street1,city1,state1
house2,street2,city2,state2
house3,street3,city3,state3
Add JSR223 PreProcessor as a child of the request you want to parameterize
Put the following code into "Script" area:
def builder = new groovy.json.JsonBuilder()
#groovy.transform.Immutable
class VILLA {
String HSENO
String STREETNO
String CITY
String STATE
}
def villas = new File("test.csv")
.readLines()
.collect { line ->
new VILLA(line.split(",")[0], line.split(",")[1], line.split(",")[2], line.split(",")[3]) }
builder(
ID:1,
DATE: 2,
VILLA: villas.collect(),
FLATS:[]
)
log.info(builder.toPrettyString())
vars.put("payload", builder.toPrettyString())
You should see generated request body in jmeter.log file and should be able to use ${payload} JMeter Variable where required to pass the generated data.
More information:
Apache Groovy - Why and How You Should Use It
Groovy: Parsing and producing JSON
JsonBuilder

JSR223 Preprocessor give Bad request while creating json in Jmeter using CSV

I am trying to create a JSON using Groovy Json Builder in Jmeter.
Below is the code I created to get the desired JSON :
import groovy.json.JsonBuilder
def json = new JsonBuilder()
json {
"Rule":{
"__type":"AndroidSamsungDeviceRelocationRule",
"RuleId":0,
"Name":"Test",
"DeviceFamily":6,
"Targets":{
"Groups":[
{
"Id":"[{LogicalId="${logicalid1}"}]"
}
],
"Devices":[
]
},
"Priority":0,
"IsEnabled":true,
"StartDate":"/Date(${__time(,)})/",
"EndDate":null,
"Mappings":[
{
"RelocationTarget":{
"Id":"${logicalid2}",
"Name":"${__P(TargetGroups)}",
"Path":"\\'${__P(TargetGroups)}'\\",
"PathVisible":"\\'${__P(TargetGroups)}'\\"
},
"IPRange":[
source Double.parseDouble(vars.get("source"))
destination Double.parseDouble(vars.get("destination"))
]
}
],
"EnrollmentCertificateId":null,
"EnrollmentCertificateName":""
}
}
sampler.addNonEncodedArgument("",json.toPrettyString(),"")
sampler.setPostBodyRaw(true)
CSV data is as follows:
0.0.0.0,255.255.255.255
10.0.0.1,255.0.0.0
The above CSV can have multiple values from 1 to 100 IPs separated by ',' .
The code also needs to be modified as per the number of IPs rows.
The ABove CSV data needs to be there under IPRange tag and Result Should be like:
"Rule":{
"__type":"AndroidSamsungDeviceRelocationRule",
"RuleId":0,
"Name":"Test",
"DeviceFamily":6,
"Targets":{
"Groups":[
{
"Id":"[{LogicalId="${logicalid1}"}]"
}
],
"Devices":[
]
},
"Priority":0,
"IsEnabled":true,
"StartDate":"/Date(${__time(,)})/",
"EndDate":null,
"Mappings":[
{
"RelocationTarget":{
"Id":"${logicalid2}",
"Name":"${__P(TargetGroups)}",
"Path":"\\'${__P(TargetGroups)}'\\",
"PathVisible":"\\'${__P(TargetGroups)}'\\"
},
"IPRange":[
{"From":"0.0.0.0","To":"255.255.255.255"},
{"From":"10.0.0.1","To":"255.0.0.1"},
......
.....
]
}
],
"EnrollmentCertificateId":null,
"EnrollmentCertificateName":""
}
But the issue I am getting is "Bad Request" in jmeter.
I fail to see why do you need to build your request body in Groovy, it can be done purely in HTTP Request "Body Data" tab like:
Check out JMeter Parameterization - The Complete Guide for examples on using external data sources for creating data-driven JMeter tests
If you want us to help you with the setup it would be good to see the desired outcome, i.e. JSON payload you would like to generate and the code you've tried as above samples don't make any sense. Get used to check jmeter.log file - normally it contains enough information to get to the bottom of the JMeter test issue. Also I suggest reading Parsing and producing JSON article and JsonBuilder class documentation.

How to load a json file with unit ML test examples into jmeter http request payload

I have an endpoint that serves a ML model and I want to perform load testing on it. I'm using Jmeter 4.0 and its UI to construct a simple plan test. With 1 thread group that loops for a given duration and continuosly performs https requests.
How do I parse multiple test examples into the payload of a http request, one by one and in json format. These examples are contained in a json file called samples.json. The nested structure is the following:
{ "dataset": [
{"id": 1,
"in":[
{
"Feature1": 8.9
"Feature2":7.1
}],
"out": "Class1",
},
{"id": 2,
"in":[
{
"Feature1": 3.2
"Feature2":5.1
}],
"out": "Class1",
}]
}
IMPORTANT: I do not know the number of attributes a priori, so I need to retrieve them from the in key as that may change for other types of models, therefore I can't make use of harcoded jmeter variables, similar to what it's used in the CSV Config Set add-on, where they need to specify the variables names for each column of the csv file
I have no idea how you're gonna use the values from JSON in the HTTP Request sampler, however this is how you can parse your samples.json file and get in values from it in the JSR223 Sampler
new groovy.json.JsonSlurper().parse(new File('samples.json')).dataset.each { entry ->
entry.get('in').each { feature ->
feature.each { value ->
log.info(value.key + '=' + value.value)
}
}
}
The above code basically prints the keys and respective values into jmeter.log file
But you can easily amend it to store the values into JMeter Variables, write them into a CSV file, set HTTP Request sampler to use them on the fly, etc.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
Apache JMeter API

Building json path expression - presence of DOT in attribute name

We are working with a legacy system which gives json responses. We trying to test these json endpoints with jmeter. So, we are trying to use the json path extractor plugin for the purpose. But the structure of the json path is causing an issue in creating json path expressions.
The structure of the json which we are receiving from the server is as follows.
{
"ns9.Shopping": {
"transactionID": "XXXXXNEKIHJO7SRHN1",
"transactionStatus": "Success",
"ns9.shoppingResponseIDs": {
"ns9.owner": "1P",
"ns9.responseId": "abcdefghijklmnop"
},
"ns9.offersGroup": {"ns9.thanksGiving": [
{
"ns9.owner": "DL",
"ns9.retailOffer": [
{
"ns9.offerId": "offer1DL",
"ns9.price": 2639.08,
"ns9.currencyCode": "USD",
"ns9.taxTotal": 961.08,
"ns9.taxCode": "USD",
.........
The presence of . [DOT] in the attribute name is causing issues in my json path expression.
In short, can some one help in finding the "transactionID" from "ns9.Shopping"?
You can try to add Regular Expression Extractor within your HTTP Request element.
Put this regex:
"transactionID": "([a-zA-Z0-9]*)"
I hope this will help you.