### Example Usage of PermittedUrlsChecker Source: https://github.com/swagger-api/swagger-parser/blob/master/modules/swagger-parser-safe-url-resolver/README.md Demonstrates how to use the PermittedUrlsChecker with custom allowlists and denylists. It shows cases that will throw exceptions and cases that will return a ResolvedUrl. ```java import io.swagger.v3.parser.urlresolver.PermittedUrlsChecker; import io.swagger.v3.parser.urlresolver.exceptions.HostDeniedException; import io.swagger.v3.parser.urlresolver.models.ResolvedUrl; import java.util.List; public class Main { public static void main() { List allowlist = List.of("mysite.local"); List denylist = List.of("*.example.com:443"); var checker = new PermittedUrlsChecker(allowlist, denylist); try { // Will throw a HostDeniedException as `localhost` // resolves to local IP and is not in allowlist checker.verify("http://localhost/example"); // Will return a ResolvedUrl if `github.com` // resolves to a public IP checker.verify("https://github.com/swagger-api/swagger-parser"); // Will throw a HostDeniedException as `*.example.com` is // explicitly deny listed, even if it resolves to public IP checker.verify("https://subdomain.example.com/somepage"); // Will return a `ResolvedUrl` as `mysite.local` // is explicitly allowlisted ResolvedUrl resolvedUrl = checker.verify("http://mysite.local/example"); System.out.println(resolvedUrl.getUrl()); // "http://127.0.0.1/example" System.out.println(resolvedUrl.getHostHeader()); // "mysite.local" } catch (HostDeniedException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Build Swagger Parser from Source Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md To build the Swagger Parser from source, ensure you have Java 11 and Apache Maven 3.x installed. Then, run the package command in the project's root directory. ```bash mvn package ``` -------------------------------- ### Unresolved OpenAPI YAML with Composed Schema Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md An example of an OpenAPI 3.0.1 YAML file containing a composed schema using `allOf`. This serves as the input for demonstrating the `resolveCombinators` option. ```yaml openapi: 3.0.1 servers: - url: http://petstore.swagger.io/api info: description: 'This is a sample server Petstore' version: 1.0.0 title: testing source file termsOfService: http://swagger.io/terms/ paths: "/withInvalidComposedModel": post: operationId: withInvalidComposedModel requestBody: content: "application/json": schema: "$ref": "#/components/schemas/ExtendedAddress" required: false responses: '200': description: success! components: schemas: ExtendedAddress: type: object allOf: - $ref: '#/components/schemas/Address' - type: object required: - gps properties: gps: type: string Address: required: - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: '94022' ``` -------------------------------- ### Initialize Swagger UI Standalone Source: https://github.com/swagger-api/swagger-parser/blob/master/modules/swagger-parser-v3/src/test/resources/issue-407/full/index.html Use this snippet to set up Swagger UI with a standalone layout. It requires the API URL and specifies various configuration options for the UI. ```javascript window.onload = function() { // Build a system apiUrl = window.location.protocol + "//" + window.location.host + "/api/v3/openapi.json"; const ui = SwaggerUIBundle({ oauth2RedirectUrl: window.location.protocol + '//' + window.location.host + '/oauth2-redirect.html', url: apiUrl, dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout", queryConfigEnabled: true }) // To use SwaggerUIBuilder a global variable like this, uncomment the line below // window.ui = ui } ``` -------------------------------- ### Original OpenAPI Document Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md This is the original OpenAPI YAML content before parsing with the flatten option. ```yaml openapi: 3.0.0 info: version: 1.0.0 title: Swagger Petstore license: name: MIT paths: /pets: get: summary: List all pets operationId: listPets responses: '200': description: An paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: type: object properties: id: type: integer format: int64 name: type: string tag: type: string ``` -------------------------------- ### Configure Swagger Parser with resolveCombinators Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Set parse options to enable full resolution and control combinator schema processing. This is useful for customizing how composed schemas are handled. ```java ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(true); // implicit parseOptions.setResolveFully(true); parseOptions.setResolveCombinators(false); // default is true final OpenAPI openAPI = new OpenAPIV3Parser().read("a.yaml", null, parseOptions); ``` -------------------------------- ### Configure Parser to Fully Resolve References Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Enables full reference resolution, replacing local references with the content of the referenced element after remote references have been resolved. This can result in larger documents. ```java ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(true); // implicit parseOptions.setResolveFully(true); final OpenAPI openAPI = new OpenAPIV3Parser().read("a.yaml", null, parseOptions); ``` -------------------------------- ### Add Dependency to pom.xml Source: https://github.com/swagger-api/swagger-parser/blob/master/modules/swagger-parser-safe-url-resolver/README.md Include this dependency in your project's pom.xml file to use the swagger-parser-safe-url-resolver library. ```xml io.swagger.parser.v3 swagger-parser-safe-url-resolver 2.1.14 ``` -------------------------------- ### Test Case for resolveCombinators = true (Default) Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md A JUnit test case demonstrating the behavior of `resolveCombinators` set to `true`. It verifies that `allOf` schemas are aggregated and properties are merged correctly. ```java @Test public void resolveAllOfWithoutAggregatingParameters(@Injectable final List auths) { ParseOptions options = new ParseOptions(); options.setResolveFully(true); options.setResolveCombinators(true); // Testing components/schemas OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/composed.yaml",auths,options).getOpenAPI(); ComposedSchema allOf = (ComposedSchema) openAPI.getComponents().getSchemas().get("ExtendedAddress"); assertEquals(allOf.getAllOf().size(), 2); assertTrue(allOf.getAllOf().get(0).get$ref() != null); assertTrue(allOf.getAllOf().get(1).getProperties().containsKey("gps")); // Testing path item ObjectSchema schema = (ObjectSchema) openAPI.getPaths().get("/withInvalidComposedModel").getPost().getRequestBody().getContent().get("application/json").getSchema(); assertEquals(schema.getProperties().size(), 5); assertTrue(schema.getProperties().containsKey("street")); assertTrue(schema.getProperties().containsKey("gps")); } ``` -------------------------------- ### Resolve OpenAPI with resolveCombinators disabled Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md This Java code snippet demonstrates parsing an OpenAPI file using `OpenAPIV3Parser`. It configures `ParseOptions` to disable full resolution of combinators (`resolveCombinators(false)`) and enable full resolution (`setResolveFully(true)`). The parsed OpenAPI object is then used to access and assert properties of a `ComposedSchema` named 'ExtendedAddress', both from components and path items. ```java public void resolveAllOfWithoutAggregatingParameters(@Injectable final List auths) { ParseOptions options = new ParseOptions(); options.setResolveFully(true); options.setResolveCombinators(false); // Testing components/schemas OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/composed.yaml",auths,options).getOpenAPI(); ComposedSchema allOf = (ComposedSchema) openAPI.getComponents().getSchemas().get("ExtendedAddress"); assertEquals(allOf.getAllOf().size(), 2); assertTrue(allOf.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(allOf.getAllOf().get(1).getProperties().containsKey("gps")); // Testing path item ComposedSchema schema = (ComposedSchema) openAPI.getPaths().get("/withInvalidComposedModel").getPost().getRequestBody().getContent().get("application/json").getSchema(); // In fact the schema resolved previously is the same of /withInvalidComposedModel assertEquals(schema, allOf); assertEquals(schema.getAllOf().size(), 2); assertTrue(schema.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(schema.getAllOf().get(1).getProperties().containsKey("gps")); } ``` -------------------------------- ### Disable SSL Trust Manager for Self-Signed Certificates Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Sets the TRUST_ALL environment variable to true to ignore invalid SSL certificates. This is generally not recommended but can be useful in controlled environments. ```bash export TRUST_ALL=true ``` -------------------------------- ### Configure Swagger Parser with explicitObjectSchema Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Set parse options to control schema resolution, including explicitObjectSchema. This option is only applied when resolveFully is true. ```java ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(true); // implicit parseOptions.setResolveFully(true); parseOptions.setResolveCombinators(false); parseOptions.setExplicitObjectSchema(false); // default is true final OpenAPI openAPI = new OpenAPIV3Parser().read("a.yaml", null, parseOptions); ``` -------------------------------- ### Add Swagger Parser Dependency Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Include the Swagger Parser library in your project by adding the following dependency to your Maven `pom.xml` file. ```xml io.swagger.parser.v3 swagger-parser 2.1.42 ``` -------------------------------- ### Directly Parse OpenAPI 3.0 with OpenAPIV3Parser Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Use OpenAPIV3Parser for direct parsing of OpenAPI 3.0 documents. This parser provides a convenience method to retrieve the OpenAPI object directly. ```java import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.oas.models.OpenAPI; // ... your code // read a swagger description from the petstore OpenAPI openAPI = new OpenAPIV3Parser().read("https://petstore3.swagger.io/api/v3/openapi.json"); ``` -------------------------------- ### Parse OpenAPI with Flatten Option Enabled Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Use this Java code to parse an OpenAPI definition with the `flatten` option set to `true`. This will inline schemas into `components/schemas`. ```java ParseOptions parseOptions = new ParseOptions(); parseOptions.setFlatten(true); final OpenAPI openAPI = new OpenAPIV3Parser().read("a.yaml", null, parseOptions); ``` -------------------------------- ### OAuth2 Redirect Handler Logic Source: https://github.com/swagger-api/swagger-parser/blob/master/modules/swagger-parser-v3/src/test/resources/issue-407/full/oauth2-redirect.html This script processes the OAuth2 redirect, extracting and validating authorization codes or tokens. It handles different OAuth2 flows and communicates results or errors back to the opener window before closing itself. ```javascript 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1); } else { qp = location.search.substring(1); } arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"'; }); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {}; isValid = qp.state === sentState; if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server" }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server" }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } if (document.readyState !== 'loading') { run(); } else { document.addEventListener('DOMContentLoaded', function () { run(); }); } ``` -------------------------------- ### Serialized OpenAPI After Flattening Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md This YAML shows the structure of the OpenAPI document after being parsed with the `flatten(true)` option. Notice how the inline schema is now a reference to `#/components/schemas/inline_response_200`. ```yaml openapi: 3.0.0 info: title: Swagger Petstore license: name: MIT version: 1.0.0 servers: - url: / paths: /pets: get: tags: - pets summary: List all pets responses: 200: description: An paged array of pets headers: x-next: description: A link to the next page of responses style: simple explode: false schema: type: string content: application/json: schema: $ref: '#/components/schemas/inline_response_200' components: schemas: inline_response_200: type: object properties: id: type: integer format: int64 name: type: string tag: type: string ``` -------------------------------- ### Configure Parser to Resolve References Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Enables reference resolution for remote or relative references within an OpenAPI document. Resolved components are added to the OpenAPI POJO, and references are replaced with local ones. ```java ParseOptions parseOptions = new ParseOptions(); parseOptions.setResolve(true); final OpenAPI openAPI = new OpenAPIV3Parser().read("a.yaml", null, parseOptions); ``` -------------------------------- ### Parse OpenAPI from Location Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Use OpenAPIParser to read an OpenAPI definition from a given URL or file path. It returns a SwaggerParseResult containing the parsed OpenAPI object and any validation messages. ```java import io.swagger.parser.OpenAPIParser; import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.parser.core.models.SwaggerParseResult; import io.swagger.v3.oas.models.OpenAPI; // ... your code // parse a swagger description from the petstore and get the result SwaggerParseResult result = new OpenAPIParser().readLocation("https://petstore3.swagger.io/api/v3/openapi.json", null, null); // or from a file // SwaggerParseResult result = new OpenAPIParser().readLocation("./path/to/openapi.yaml", null, null); // the parsed POJO OpenAPI openAPI = result.getOpenAPI(); if (result.getMessages() != null) result.getMessages().forEach(System.err::println); // validation errors and warnings if (openAPI != null) { ... } ``` -------------------------------- ### Resolved OpenAPI YAML with resolveCombinators = true Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md The resulting OpenAPI YAML after parsing with `resolveCombinators` set to `true`. This shows how composed schemas are flattened and properties are merged into a single schema. ```yaml openapi: 3.0.1 info: title: testing source file description: This is a sample server Petstore termsOfService: http://swagger.io/terms/ version: 1.0.0 servers: - url: http://petstore.swagger.io/api paths: /withInvalidComposedModel: post: operationId: withInvalidComposedModel requestBody: content: application/json: schema: required: - gps - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: "94022" gps: type: string required: false responses: 200: description: success! components: schemas: ExtendedAddress: type: object allOf: - $ref: '#/components/schemas/Address' - required: - gps type: object properties: gps: type: string Address: required: - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: "94022" ``` -------------------------------- ### Parse Swagger/OpenAPI 2.0 Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md When parsing a Swagger/OpenAPI 2.0 document using OpenAPIParser, it is automatically converted to an OpenAPI 3.0 compatible format. ```java SwaggerParseResult result = new OpenAPIParser().readContents("./path/to/swagger.yaml", null, null); ``` -------------------------------- ### Parse OpenAPI from String Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Use OpenAPIParser to read an OpenAPI definition directly from a string. This is useful when the definition is available in memory. It returns a SwaggerParseResult. ```java import io.swagger.parser.OpenAPIParser; import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.parser.core.models.SwaggerParseResult; import io.swagger.v3.oas.models.OpenAPI; // ... your code // parse a swagger description from the petstore and get the result SwaggerParseResult result = new OpenAPIParser().readContents("https://petstore3.swagger.io/api/v3/openapi.json", null, null); // or from a file // SwaggerParseResult result = new OpenAPIParser().readContents("./path/to/openapi.yaml", null, null); // the parsed POJO OpenAPI openAPI = result.getOpenAPI(); if (result.getMessages() != null) result.getMessages().forEach(System.err::println); // validation errors and warnings if (openAPI != null) { ... } ``` -------------------------------- ### Resolved OpenAPI YAML with resolveCombinators = false Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md This YAML snippet represents an OpenAPI 3.0.1 specification. It defines a path '/withInvalidComposedModel' and a schema 'ExtendedAddress' that uses 'allOf' to combine multiple schema definitions. The 'resolveCombinators: false' option in the parser means that the 'allOf' combinator is not fully resolved into a single schema object during parsing. ```yaml openapi: 3.0.1 info: title: testing source file description: This is a sample server Petstore termsOfService: http://swagger.io/terms/ version: 1.0.0 servers: - url: http://petstore.swagger.io/api paths: /withInvalidComposedModel: post: operationId: withInvalidComposedModel requestBody: content: application/json: schema: type: object allOf: - required: - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: "94022" - required: - gps type: object properties: gps: type: string required: false responses: 200: description: success! components: schemas: ExtendedAddress: type: object allOf: - required: - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: "94022" - required: - gps type: object properties: gps: type: string Address: required: - street type: object properties: street: type: string example: 12345 El Monte Road city: type: string example: Los Altos Hills state: type: string example: CA zip: type: string example: "94022" ``` -------------------------------- ### Test Case for resolveCombinators = false Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md A JUnit test case for the scenario where `resolveCombinators` is set to `false`. This configuration preserves the composed nature of schemas, rather than merging them. ```java @Test ``` -------------------------------- ### Build Authorization Value for Authenticated Requests Source: https://github.com/swagger-api/swagger-parser/blob/master/README.md Constructs an AuthorizationValue object to pass custom headers for protected OpenAPI definitions. Supports specifying key name, value, and type (header or query). ```java import io.swagger.v3.parser.core.models.AuthorizationValue; // ... your code // build a authorization value AuthorizationValue mySpecialHeader = new AuthorizationValue() .keyName("x-special-access") // the name of the authorization to pass .value("i-am-special") // the value of the authorization .type("header"); // the location, as either `header` or `query` // or in a single constructor AuthorizationValue apiKey = new AuthorizationValue("api_key", "special-key", "header"); OpenAPI openAPI = new OpenAPIV3Parser().readWithInfo( "https://petstore3.swagger.io/api/v3/openapi.json", Arrays.asList(mySpecialHeader, apiKey) ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.