Search in sources :

Example 1 with Header

use of io.swagger.v3.oas.annotations.headers.Header in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method testSecurityDefinition.

@Test
public void testSecurityDefinition() {
    String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "paths:\n" + "  /pet:\n" + "    get:\n" + "      security:\n" + "        - basic_auth: []\n" + "          api_key: []\n" + "      responses:\n" + "        default:\n" + "          description: Default response\n" + "info:\n" + "  version: ''\n" + "  title: ''\n" + "components:\n" + "  securitySchemes:\n" + "    basic_auth:\n" + "      type: http\n" + "      x-foo: basicBar\n" + "      scheme: basic\n" + "    api_key:\n" + "      type: apiKey\n" + "      name: api_key\n" + "      in: header\n" + "      description: api key description\n" + "      x-foo: apiKeyBar";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI.getComponents().getSecuritySchemes());
    assertTrue(openAPI.getComponents().getSecuritySchemes().keySet().size() == 2);
    // Basic Authentication
    SecurityScheme definitionBasic = openAPI.getComponents().getSecuritySchemes().get("basic_auth");
    assertNotNull(definitionBasic);
    assertEquals(definitionBasic.getType(), SecurityScheme.Type.HTTP);
    assertEquals(definitionBasic.getExtensions().get("x-foo"), "basicBar");
    // API Key Authentication
    SecurityScheme definition = openAPI.getComponents().getSecuritySchemes().get("api_key");
    assertNotNull(definition);
    assertEquals(definition.getType(), SecurityScheme.Type.APIKEY);
    SecurityScheme apiKey = definition;
    assertEquals(apiKey.getName(), "api_key");
    assertEquals(apiKey.getIn(), SecurityScheme.In.HEADER);
    assertEquals(apiKey.getDescription(), "api key description");
    assertEquals(apiKey.getExtensions().get("x-foo"), "apiKeyBar");
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Test(org.testng.annotations.Test)

Example 2 with Header

use of io.swagger.v3.oas.annotations.headers.Header in project swagger-parser by swagger-api.

the class NetworkReferenceTest method testIssue411.

@Test
public void testIssue411() throws Exception {
    final List<AuthorizationValue> auths = new ArrayList<>();
    AuthorizationValue auth = new AuthorizationValue("Authorization", "OMG_SO_SEKR3T", "header");
    auths.add(auth);
    new Expectations() {

        {
            remoteUrl.urlToString("http://remote1/resources/swagger.yaml", auths);
            result = issue_411_server;
            remoteUrl.urlToString("http://remote2/resources/foo", auths);
            result = issue_411_components;
        }
    };
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult result = parser.readLocation("http://remote1/resources/swagger.yaml", auths, options);
    OpenAPI swagger = result.getOpenAPI();
    assertNotNull(swagger.getPaths().get("/health"));
    PathItem health = swagger.getPaths().get("/health");
    assertTrue(health.getGet().getParameters().size() == 0);
    Schema responseRef = health.getGet().getResponses().get("200").getContent().get("*/*").getSchema();
    assertTrue(responseRef.get$ref() != null);
    assertEquals(responseRef.get$ref(), "#/components/schemas/Success");
    assertNotNull(swagger.getComponents().getSchemas().get("Success"));
    Parameter param = swagger.getPaths().get("/stuff").getGet().getParameters().get(0);
    assertEquals(param.getIn(), "query");
    assertEquals(param.getName(), "skip");
    ApiResponse response = swagger.getPaths().get("/stuff").getGet().getResponses().get("200");
    assertNotNull(response);
    assertTrue(response.getContent().get("*/*").getSchema() instanceof StringSchema);
    ApiResponse error = swagger.getPaths().get("/stuff").getGet().getResponses().get("400");
    assertNotNull(error);
    Schema errorProp = error.getContent().get("*/*").getSchema();
    assertNotNull(errorProp);
    assertTrue(errorProp.get$ref() != null);
    assertEquals(errorProp.get$ref(), "#/components/schemas/Error");
    assertTrue(swagger.getComponents().getSchemas().get("Error") instanceof Schema);
}
Also used : Expectations(mockit.Expectations) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) AuthorizationValue(io.swagger.v3.parser.core.models.AuthorizationValue) PathItem(io.swagger.v3.oas.models.PathItem) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) Parameter(io.swagger.v3.oas.models.parameters.Parameter) StringSchema(io.swagger.v3.oas.models.media.StringSchema) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 3 with Header

use of io.swagger.v3.oas.annotations.headers.Header in project swagger-parser by swagger-api.

the class NetworkReferenceTest method testValidateExternalRefsTrueRemote.

@Test(description = "option true, adds Original Location to messages when ref is remote")
public void testValidateExternalRefsTrueRemote() throws Exception {
    ParseOptions options = new ParseOptions();
    options.setValidateExternalRefs(true);
    options.setResolve(true);
    new Expectations() {

        {
            remoteUrl.urlToString("http://localhost:8080/swos-443/root.yaml", new ArrayList<>());
            result = issue_443_yaml;
            remoteUrl.urlToString("http://localhost:8080/swos-443/ref.yaml", new ArrayList<>());
            result = issue_443_ref_yaml;
        }
    };
    SwaggerParseResult result = new OpenAPIV3Parser().readLocation("http://localhost:8080/swos-443/root.yaml", null, options);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(result.getMessages());
    assertEquals(result.getMessages().size(), 19);
    assertNotNull(openAPI);
    assertTrue(result.getMessages().contains("attribute components.requestBodies.NewItem.asdasd is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.requestBodies.NewItem.descasdasdription is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.responses.GeneralError.descrsaiption is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.responses.GeneralError.asdas is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.responses.GeneralError.description is missing (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.schemas.Examples.nonExpected is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.parameters.skipParam.[skip].in is not of type `[query|header|path|cookie]` (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.securitySchemes.api_key.namex is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.securitySchemes.api_key.name is missing (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.callbacks.webhookVerificationEvent.postx is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.headers.X-Rate-Limit-Limit.descriptasdd is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.links.unsubscribe.parametersx is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.examples.response-example.summaryx is unexpected (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.examples.response-example. value and externalValue are both present (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute components.callbacks.failed.wrongField is not of type `object` (./ref.yaml)"));
    assertTrue(result.getMessages().contains("attribute paths.~1refPet(get).responses is missing (./ref.yaml)"));
    // error message in main file
    assertTrue(result.getMessages().contains("attribute components.schemas.InvalidSchema.invalid is unexpected"));
}
Also used : Expectations(mockit.Expectations) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 4 with Header

use of io.swagger.v3.oas.annotations.headers.Header in project swagger-parser by swagger-api.

the class OpenAPIDeserializer method getParameter.

public Parameter getParameter(ObjectNode obj, String location, ParseResult result) {
    if (obj == null) {
        return null;
    }
    Parameter parameter = null;
    JsonNode ref = obj.get("$ref");
    if (ref != null) {
        if (ref.getNodeType().equals(JsonNodeType.STRING)) {
            parameter = new Parameter();
            String mungedRef = mungedRef(ref.textValue());
            if (mungedRef != null) {
                parameter.set$ref(mungedRef);
            } else {
                parameter.set$ref(ref.textValue());
            }
            return parameter;
        } else {
            result.invalidType(location, "$ref", "string", obj);
            return null;
        }
    }
    String l = null;
    JsonNode ln = obj.get("name");
    if (ln != null) {
        l = ln.asText();
    } else {
        l = "['unknown']";
    }
    location += ".[" + l + "]";
    String value = getString("in", obj, true, location, result);
    if (!result.isAllowEmptyStrings() && StringUtils.isBlank(value) || result.isAllowEmptyStrings() && value == null) {
        return null;
    }
    if (QUERY_PARAMETER.equals(value)) {
        parameter = new QueryParameter();
    } else if (HEADER_PARAMETER.equals(value)) {
        parameter = new HeaderParameter();
    } else if (PATH_PARAMETER.equals(value)) {
        parameter = new PathParameter();
    } else if (COOKIE_PARAMETER.equals(value)) {
        parameter = new CookieParameter();
    }
    if (parameter == null) {
        result.invalidType(location, "in", "[query|header|path|cookie]", obj);
        return null;
    }
    parameter.setIn(value);
    value = getString("name", obj, true, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        parameter.setName(value);
    }
    value = getString("description", obj, false, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        parameter.setDescription(value);
    }
    Boolean required = getBoolean("required", obj, false, location, result);
    if (required != null) {
        parameter.setRequired(required);
    } else {
        parameter.setRequired(false);
    }
    Boolean deprecated = getBoolean("deprecated", obj, false, location, result);
    if (deprecated != null) {
        parameter.setDeprecated(deprecated);
    }
    if (parameter instanceof QueryParameter) {
        Boolean allowEmptyValue = getBoolean("allowEmptyValue", obj, false, location, result);
        if (allowEmptyValue != null) {
            parameter.setAllowEmptyValue(allowEmptyValue);
        }
    }
    value = getString("style", obj, false, location, result);
    setStyle(value, parameter, location, obj, result);
    Boolean explode = getBoolean("explode", obj, false, location, result);
    if (explode != null) {
        parameter.setExplode(explode);
    } else if (StyleEnum.FORM.equals(parameter.getStyle())) {
        parameter.setExplode(Boolean.TRUE);
    } else {
        parameter.setExplode(Boolean.FALSE);
    }
    ObjectNode parameterObject = getObject("schema", obj, false, location, result);
    if (parameterObject != null) {
        parameter.setSchema(getSchema(parameterObject, String.format("%s.%s", location, "schemas"), result));
    }
    ObjectNode examplesObject = getObject("examples", obj, false, location, result);
    if (examplesObject != null) {
        parameter.setExamples(getExamples(examplesObject, String.format("%s.%s", location, "examples"), result, false));
    }
    Object example = getAnyExample("example", obj, location, result);
    if (example != null) {
        if (examplesObject != null) {
            result.warning(location, "examples already defined -- ignoring \"example\" field");
        } else {
            parameter.setExample(example instanceof NullNode ? null : example);
        }
    }
    Boolean allowReserved = getBoolean("allowReserved", obj, false, location, result);
    if (allowReserved != null) {
        parameter.setAllowReserved(allowReserved);
    }
    ObjectNode contentNode = getObject("content", obj, false, location, result);
    if (contentNode != null) {
        Content content = getContent(contentNode, String.format("%s.%s", location, "content"), result);
        if (content.size() == 0) {
            result.unsupported(location, "content with no media type", contentNode);
            result.invalid();
        } else if (content.size() > 1) {
            result.unsupported(location, "content with multiple media types", contentNode);
            result.invalid();
        } else if (parameter.getSchema() != null) {
            result.unsupported(location, "content when schema defined", contentNode);
            result.invalid();
        } else {
            parameter.setContent(content);
        }
    } else if (parameter.getSchema() == null) {
        result.missing(location, "content");
    }
    Map<String, Object> extensions = getExtensions(obj);
    if (extensions != null && extensions.size() > 0) {
        parameter.setExtensions(extensions);
    }
    Set<String> keys = getKeys(obj);
    for (String key : keys) {
        if (!PARAMETER_KEYS.contains(key) && !key.startsWith("x-")) {
            result.extra(location, key, obj.get(key));
        }
    }
    return parameter;
}
Also used : QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) Content(io.swagger.v3.oas.models.media.Content) Parameter(io.swagger.v3.oas.models.parameters.Parameter) CookieParameter(io.swagger.v3.oas.models.parameters.CookieParameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) CookieParameter(io.swagger.v3.oas.models.parameters.CookieParameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) NullNode(com.fasterxml.jackson.databind.node.NullNode)

Example 5 with Header

use of io.swagger.v3.oas.annotations.headers.Header in project swagger-parser by swagger-api.

the class OpenAPIV3ParserTest method doRelativeFileTest.

private OpenAPI doRelativeFileTest(String location) {
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    SwaggerParseResult readResult = parser.readLocation(location, null, options);
    if (readResult.getMessages().size() > 0) {
        Json.prettyPrint(readResult.getMessages());
    }
    final OpenAPI openAPI = readResult.getOpenAPI();
    final PathItem path = openAPI.getPaths().get("/health");
    // we successfully converted the RefPath to a Path
    assertEquals(path.getClass(), PathItem.class);
    final List<Parameter> parameters = path.getParameters();
    assertParamDetails(parameters, 0, QueryParameter.class, "param1", "query");
    assertParamDetails(parameters, 1, HeaderParameter.class, "param2", "header");
    final Operation operation = path.getGet();
    final List<Parameter> operationParams = operation.getParameters();
    assertParamDetails(operationParams, 0, PathParameter.class, "param3", "path");
    assertParamDetails(operationParams, 1, HeaderParameter.class, "param4", "header");
    final Map<String, ApiResponse> responsesMap = operation.getResponses();
    assertResponse(openAPI, responsesMap, "200", "application/json", "Health information from the server", "#/components/schemas/health");
    assertResponse(openAPI, responsesMap, "400", "*/*", "Your request was not valid", "#/components/schemas/error");
    assertResponse(openAPI, responsesMap, "500", "*/*", "An unexpected error occur during processing", "#/components/schemas/error");
    final Map<String, Schema> definitions = openAPI.getComponents().getSchemas();
    final Schema refInDefinitions = definitions.get("refInDefinitions");
    assertEquals(refInDefinitions.getDescription(), "The example model");
    expectedPropertiesInModel(refInDefinitions, "foo", "bar");
    final ArraySchema arrayModel = (ArraySchema) definitions.get("arrayModel");
    final Schema arrayModelItems = arrayModel.getItems();
    assertEquals(arrayModelItems.get$ref(), "#/components/schemas/foo");
    final Schema fooModel = definitions.get("foo");
    assertEquals(fooModel.getDescription(), "Just another model");
    expectedPropertiesInModel(fooModel, "hello", "world");
    final ComposedSchema composedCat = (ComposedSchema) definitions.get("composedCat");
    final Schema child = composedCat.getAllOf().get(2);
    expectedPropertiesInModel(child, "huntingSkill", "prop2", "reflexes", "reflexMap");
    final ArraySchema reflexes = (ArraySchema) child.getProperties().get("reflexes");
    final Schema reflexItems = reflexes.getItems();
    assertEquals(reflexItems.get$ref(), "#/components/schemas/reflex");
    assertTrue(definitions.containsKey(reflexItems.get$ref().substring(reflexItems.get$ref().lastIndexOf("/") + 1)));
    final Schema reflexMap = (Schema) child.getProperties().get("reflexMap");
    final Schema reflexMapAdditionalProperties = (Schema) reflexMap.getAdditionalProperties();
    assertEquals(reflexMapAdditionalProperties.get$ref(), "#/components/schemas/reflex");
    assertEquals(composedCat.getAllOf().size(), 3);
    assertEquals(composedCat.getAllOf().get(0).get$ref(), "#/components/schemas/pet");
    assertEquals(composedCat.getAllOf().get(1).get$ref(), "#/components/schemas/foo_1");
    return openAPI;
}
Also used : ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) MapSchema(io.swagger.v3.oas.models.media.MapSchema) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) PathItem(io.swagger.v3.oas.models.PathItem) ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Aggregations

Test (org.testng.annotations.Test)32 OpenAPI (io.swagger.v3.oas.models.OpenAPI)26 Header (io.swagger.v3.oas.models.headers.Header)25 Parameter (io.swagger.v3.oas.models.parameters.Parameter)16 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)13 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)11 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)11 Schema (io.swagger.v3.oas.models.media.Schema)10 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)10 MediaType (io.swagger.v3.oas.models.media.MediaType)8 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)8 Components (io.swagger.v3.oas.models.Components)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 StringSchema (io.swagger.v3.oas.models.media.StringSchema)6 AuthorizationValue (io.swagger.v3.parser.core.models.AuthorizationValue)6 PathItem (io.swagger.v3.oas.models.PathItem)5 Example (io.swagger.v3.oas.models.examples.Example)5 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)5 PathParameter (io.swagger.v3.oas.models.parameters.PathParameter)5 RefFormat (io.swagger.v3.parser.models.RefFormat)5