I\'m building a fuzzer for a REST API that has an OpenAPI (Swagger) definition.
I want to test all available path from the OpenAPI definition, generate data to test
The Swagger Inflector library has the ExampleBuilder class exactly for this purpose. It lets you generate JSON, XML and YAML examples from models in an OpenAPI (Swagger) definition.
import io.swagger.parser.SwaggerParser;
import io.swagger.models.*;
import io.swagger.inflector.examples.*;
import io.swagger.inflector.examples.models.Example;
import io.swagger.inflector.processors.JsonNodeExampleSerializer;
import io.swagger.util.Json;
import io.swagger.util.Yaml;
import java.util.Map;
import com.fasterxml.jackson.databind.module.SimpleModule;
...
// Load your OpenAPI/Swagger definition
Swagger swagger = new SwaggerParser().read("http://petstore.swagger.io/v2/swagger.json");
// Create an Example object for the Pet model
Map<String, Model> definitions = swagger.getDefinitions();
Model pet = definitions.get("Pet");
Example example = ExampleBuilder.fromModel("Pet", pet, definitions, new HashSet<String>());
// Another way:
// Example example = ExampleBuilder.fromProperty(new RefProperty("Pet"), swagger.getDefinitions());
// Configure example serializers
SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
Json.mapper().registerModule(simpleModule);
Yaml.mapper().registerModule(simpleModule);
// Convert the Example object to string
// JSON example
String jsonExample = Json.pretty(example);
System.out.println(jsonExample);
// YAML example
String yamlExample = Yaml.pretty().writeValueAsString(example);
System.out.println(yamlExample);
// XML example (TODO: pretty-print it)
String xmlExample = new XmlExampleSerializer().serialize(example);
System.out.println(xmlExample);
The example above uses Swagger Java libraries 1.x, which support OpenAPI 2.0 definitions (swagger: '2.0'
).
If your API definition is OpenAPI 3.0 (openapi: 3.0.0
), you need to use version 2.x of Swagger Java libraries, and update the imports and class names appropriately, e.g. io.swagger.parser.SwaggerParser
→ io.swagger.v3.parser.OpenAPIV3Parser
, etc.
My experience:
In short: generating client (java-client in my case) based on Swagger definition, filling it's model and marshalling the result.