Swagger shows extra parameters in request body - swagger

We are using springfox-swagger-ui and springfox-swagger2 of version 2.7.0.
A post api has the following signature :
#ApiOperation("Edits information about employees")
#PostMapping(path = "/employee/edit", headers = EndPoints.VERSION_1)
#ApiResponses(value = {
#ApiResponse(code = 409, message = "Data mismatch"),
#ApiResponse(code = 400, message = "Invalid data passed")
})
public ResponseEntity<Employee> manageEmployee(
#RequestHeader("employeeId") final String iEmployeeId,
#RequestBody(required = true) #Valid final Employee iEmployee)
The object employee is:
public class Employee implements Serializable {
private static final long serialVersionUID = -7315844547195801413L;
private String employeeName;
private Long employeeId;
private #Valid #NotNull List<Address> addresses;
// getter and setter methods
#Validated
public static class Address implements Serializable {
private static final long serialVersionUID = 6748945632164495934L;
private String addressId;
#ValidAddress
private String addressName;
//getter and setter methods
}
}
But the swagger shows the request body as :
{
"addresses": {
"addressId": "string",
"addressName": "string",
"permanentAddress": [
{
"addressId": "string",
"addressName": "string"
}
]
},
"employeeName": "string",
"employeeId": 0
}
The object permanentAddress is not present in my code.
How can this be resolved?

Before questioning why permantnAddress, I think it's more important to find out why addresses is an object of addressId, addressName, and a list of Address. Something doesn't look right in the JSON.
The Employee object looks like:
{
addresses: [
addressId: "string",
addressName: "string"
],
employeeName: "string",
employeeId: 0
}
permanentAddress is the correct object for List addresses

Related

RestAssured: How to validate response body with JSON schema if response body has extra values?

I am validating json schema using matchesJsonSchemaInClasspath. It is working fine if response body have the same values that are defined in schema.json file.
If response body have EXTRA variable / value which is not define in json schema then it does not fail. How to fail this test case?
FOR EXAMPLE:
Below is response body which has predefined JSON schema.
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
If response body gives extra values such as email / phone then it is still passing. I need to make it fail.This is my test case to fail if response body return extra value. How to validate this test case?
{
"employee": {
"name": "Mike",
"salary": 56000,
"Phone": "+XXX",
"email": "test#gmail.com",
"married": true
}
}
Create a POJO class representing the json
public class Employee {
private String name;
private float salary;
private boolean married;
// Getter Methods
public String getName() {
return name;
}
public float getSalary() {
return salary;
}
public boolean getMarried() {
return married;
}
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setSalary(float salary) {
this.salary = salary;
}
public void setMarried(boolean married) {
this.married = married;
}
}
Use the following rest assured command to deserialize the response
Employee emp = response.getBody().as(Employee.class);
The above command will automatically fail and throw an error when additional field such as email or phone number is added to response body.

Do I use Strategy pattern correctly in my dart code?

I'm trying to apply a strategy pattern in my dart code, but I don't know why the overridden method in child class doesn't get called.
Below is an example push notification message that will be sent to mobile devices, the data in "content" node can be different depends on the "type" value. In order to deserialize the message correctly, I created classes as below,
{
"priority": "high",
"to": "123342"
"notification": {
"body": "this is a body",
"title": "this is a title"
},
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"status": "done",
"type": "Order",
"content" : {
"order_id" : "[order_id]"
}
},
}
class Message<T extends BaseDataContent> {
String to;
String priority;
Notification notification;
Data<T> data;
Message({this.to, this.priority, this.notification, this.data});
Message.fromJson(Map<String, dynamic> json) {
to = json['to'];
priority = json['priority'];
notification = json['notification'] != null
? new Notification.fromJson(json['notification'])
: null;
data = json['data'] != null
? new Data.fromJson(json['data'])
: null;
}
}
class Notification {
String title;
String body;
Notification({this.title, this.body});
Notification.fromJson(Map<String, dynamic> json) {
title = json['title'];
body = json['body'];
}
}
class Data<T extends BaseDataContent> {
String click_action;
String status;
String type;
T content;
Data({this.click_action, this.status, this.type, this.content});
Data.fromJson(Map<String, dynamic> json) {
click_action = json['click_action'];
status = json['status'];
type = json['type'];
content = json['content'] != null?
this.content.deserializeContent(json['content'])
: null;
}
}
abstract class BaseDataContent{
BaseDataContent deserializeContent(Map<String, dynamic> jsonString);
}
class OrderMessageContent extends BaseDataContent {
int orderId;
OrderMessageContent({this.orderId}) : super();
#override
OrderMessageContent deserializeContent(Map<String, dynamic> jsonString){
///Deserialize Content json.
}
}
To test my code, I wrote some demo code as below
String json = '{"priority": "high", "to": "343434", "data":{"click_action":"343434","content":{"order_id" : "1234"}}}';
var jsonResponse = jsonDecode(json);
var result = Message<OrderMessageContent>.fromJson(jsonResponse);
The code is failed when it reaches to line
this.content.deserializeContent(json['content'])
The error message is "NoSuchMethodError: the method deserializeContent was called on null. Receiver:null". I don't know why deserializeContent method in OrderMessageContent doesn't get called, please help.
Thanks.
In Data constructor you called a method on a null object, where you called deserializeContent. You should either make that method static or initialize content first.
Data.fromJson(Map<String, dynamic> json) {
click_action = json['click_action'];
status = json['status'];
type = json['type'];
content = json['content'] != null?
this.content.deserializeContent(json['content'])
: null;
}

Convert a class into JSON or List

How to convert this class into JSON or List?
class cliente {
int id;
String nome;
String apelido;
String sexo;
String status;
}
Edit
I'm changed my class and works fine to my case:
class client {
Map<String, dynamic> fields => {
"id": "",
"name": "",
"nickname": "",
"sex": "",
"status": "",
}
Then I use:
client.fields["id"] = 1;
client.fields["name"] = "matheus";
sqlite.rowInsert("insert into client(id, name)", client.fields.Keys.toList(), client.fields.Values.toList());
Just create a method inside your class and return a Map<String, dynamic>
class cliente {
int id;
String nome;
String apelido;
String sexo;
String status;
Map<String, dynamic> toJson() => {
'id': id,
'nome': nome,
'apelido': apelido,
'sexo': sexo,
'status': status,
};
}
And use it for example :
final dataObject = new client();
...fill your object
final jsonData = dataObject.toJson();
Also you can try using this package to avoid writing all of your fields : https://pub.dartlang.org/packages/json_serializable

Need help to parsing JSON in Flutter

I am trying to get data from the internet in Flutter.
But I am getting an error on JSON parsing.
Can anyone tell me what is the problem?
I am trying to get data from this URL
https://swapi.co/api/starships/
Example JSON
{
"count": 37,
"next": "https://swapi.co/api/starships/?page=2",
"previous": null,
"results": [
{
"name": "Executor",
"model": "Executor-class star dreadnought",
"manufacturer": "Kuat Drive Yards, Fondor Shipyards",
"cost_in_credits": "1143350000",
"length": "19000",
"max_atmosphering_speed": "n/a",
"crew": "279144",
"passengers": "38000",
"cargo_capacity": "250000000",
"consumables": "6 years",
"hyperdrive_rating": "2.0",
"MGLT": "40",
"starship_class": "Star dreadnought",
"pilots": [],
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/3/"
],
"created": "2014-12-15T12:31:42.547000Z",
"edited": "2017-04-19T10:56:06.685592Z",
"url": "https://swapi.co/api/starships/15/"
},
]
}
Model class
class RestModel {
final String name;
final String model;
final String manufacturer;
final String cost_in_credits;
final String length;
final String max_atmosphering_speed;
final String crew;
final String passengers;
final String cargo_capacity;
final String consumables;
final String hyperdrive_rating;
final String MGLT;
final String starship_class;
final List films;
final String pilots;
final String created;
final String edited;
final String url;
RestModel(
{this.name,
this.model,
this.manufacturer,
this.cost_in_credits,
this.length,
this.max_atmosphering_speed,
this.crew,
this.passengers,
this.cargo_capacity,
this.consumables,
this.hyperdrive_rating,
this.MGLT,
this.starship_class,
this.films,
this.pilots,
this.created,
this.edited,
this.url});
factory RestModel.fromJson(Map<String, dynamic> json) {
return RestModel(
name: json["name"],
model: json["model"],
manufacturer: json["manufacturer"],
cost_in_credits: json["cost_in_credits"],
max_atmosphering_speed: json["max_atmosphering_speed"],
crew: json["crew"],
passengers: json["passengers"],
cargo_capacity: json["cargo_capacity"],
consumables: json["consumables"],
hyperdrive_rating: json["hyperdrive_rating"],
MGLT: json["MGLT"],
starship_class: json["starship_class"],
films: json["flims"],
pilots: json["pilots"],
created: json["created"],
edited: json["edited"],
url: json["url"],
);
}
}
and the Flutter code is:
final link = "https://swapi.co/api/starships/";
List<RestModel> list;
Future getData() async {
var res = await http
.get(Uri.encodeFull(link), headers: {"Accept":"application/json"});
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["results"];
for (var model in rest) {
list.add(RestModel.fromJson(model));
}
print("List Size: ${list.length}");
}
}
The main problem is when it tries to fill data from JSON.
RestModel.fromJson(model)
so what I have to change to fix this problem.
Try to cast the data 'results' to List , like this :
var rest = data["results"] as List;
Updated
Now that we know the error log: "No static method 'fromJson' declared in class 'RestModel'"
It's because you are using a static method in this line:
list.add(RestModel.fromJson(model));
You must change the call in order to use the factory constructor, like this :
list.add(new RestModel.fromJson(model));

Spring Data Rest Neo4j: Template must not be null or empty

I am creating what I believe to be a fairly simple domain model in Spring.
#NodeEntity
class Dependency {
#GraphId
private Long id
String groupId
String artifactId
String version
#Fetch
#RelatedTo(type = "DEPENDS_ON", direction = OUTGOING)
Set<Dependency> dependencies = new HashSet<Dependency>()
}
note* the above is written in groovy.
I have also created a subsequent Repository (all textbook so far!).
#RepositoryRestResource(collectionResourceRel = "dependency", path = "dependency")
interface DependencyRepository extends PagingAndSortingRepository<Dependency, Long> {
List<Dependency> findByArtifactId(#Param("artifactId") String artifactId)
}
And finally the application class....
#EnableNeo4jRepositories(basePackages = "io.byteshifter.depsgraph")
#SpringBootApplication
class Application extends Neo4jConfiguration {
public Application() {
setBasePackage("io.byteshifter.depsgraph")
}
#Bean(destroyMethod = "shutdown")
GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("target/dependency.db")
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application, args)
}
}
Now I would expect when I fire the following payload at http://127.0.0.1:8080/dependency that it would create all the objects and relationships..
{
"groupId": "group1",
"artifactId": "artifact1",
"version": "1.0",
"dependencies" : [
{"groupId": "group2", "artifactId": "artifact2", "version": "2.0"},
{"groupId": "group3", "artifactId": "artifact3", "version": "3.0"}
]
}
Instead, I get..
{
"cause": {
"cause": {
"cause": null,
"message": "Template must not be null or empty!"
},
"message": "Template must not be null or empty! (through reference chain: io.byteshifter.depsgraph.domain.Dependency[\"dependencies\"]->java.util.LinkedHashSet[0])"
},
"message": "Could not read JSON: Template must not be null or empty! (through reference chain: io.byteshifter.depsgraph.domain.Dependency[\"dependencies\"]->java.util.LinkedHashSet[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Template must not be null or empty! (through reference chain: io.byteshifter.depsgraph.domain.Dependency[\"dependencies\"]->java.util.LinkedHashSet[0])"
}
I have no doubt this is a lack of understanding on my behalf. If anyone could help steer me in the right direction that would be very welcomed.
My REST knowledge has failed me. I should have been using a URI to represent other dependencies. See below:
{
"groupId": "group3",
"artifactId": "artifact3",
"version": "1.0",
"dependencies": ["http://127.0.0.1:8080/dependency/0", "http://127.0.0.1:8080/dependency/1", "http://127.0.0.1:8080/dependency/2"]
}

Resources