splitting swagger definition across many files - api

Question: how can I split swagger definition across files? What are the possibilities in that area? The question details are described below:
example of what I want - in RAML
I do have experience in RAML and what I do is, for example:
/settings:
description: |
This resource defines application & components configuration
get:
is: [ includingCustomHeaders ]
description: |
Fetch entire configuration
responses:
200:
body:
example: !include samples/settings.json
schema: !include schemas/settings.json
The last two lines are important here - theones with !include <filepath> - in RAML I can split my entire contract into many files that just get included dynamically by the RAML parser (and RAML parser is used by all tools that base on RAML).
My benefit from this is that:
I get my contract more clear and easier to maintain, because schemas are not inline
but that's really important: I can reuse the schema files within other tools to do validation, mock generation, stubs, generate tests, etc. In other words, this way I can reuse schema files within both contract (RAML, this case) and other tools (non-RAML, non-swagger, just JSONschema-based ones).
back to Swagger
As far as I read, swagger supports $ref keyword which allows to load external files. But is that files fetched through HTTP/AJAX or can they just be local files?
And is that supported by the whole specification or is it just some tools that support it and some that don't?
What I found here is that the input for swagger has to be one file. And this is extremely inconvenient for big projects:
because of size
and because I can't reuse the schema if I want to use something non-swagger
Or, in other words, can I achieve the same with swagger, that I can with RAML - in terms of splitting files?

The specification allows for references in multiple locations but not everywhere. These references are resolved depending on where the specification is being hosted--and what you're trying to do.
For something like rendering a dynamic user interface, then yes you do need to eventually load the entire definition into "a single object" which may be composed from many files. If performing a code generation, the definitions may be loaded directly from the file system. But ultimately there are swagger parsers doing the resolution, which is much more fine grained and controllable in Swagger than other definition formats.
In your case, you would use a JSON pointer to the schema reference:
responses:
200:
description: the response
schema:
via local reference
$ref: '#/definitions/myModel'
via absolute reference:
$ref: 'http://path/to/your/resource'
via relative reference, which would be 'relative to where this doc is loaded'
$ref: 'resource.json#/myModel
via inline definition
type: object
properties:
id:
type: string

When I split OpenAPI V3 files using references, I try to avoid the sock drawer anti-pattern and instead use functional groupings for the YAML files.
I also make it so that each YAML file itself is a valid OpenAPI V3 spec.
I start out with the openapi.yaml file.
openapi: 3.0.3
info:
title: MyAPI
description: |
This is the public API for my stuff.
version: "3"
tags:
# NOTE: the name is needed as the info block uses `title` rather than name
- name: Authentication
$ref: 'authn.yaml#/info'
paths:
# NOTE: here are the references to the other OpenAPI files
# from the path. Note because OpenAPI requires paths to
# start with `/` and that is already used as a separator
# replace the `/` with `%2F` for the path reference.
'/authn/start':
$ref: 'authn.yaml#/paths/%2Fstart'
Then in the functional group:
openapi: 3.0.3
info:
title: Authentication
description: |
This is the authentication module.
version: "3"
paths:
# NOTE: don't include the `/authn` prefix here that top level grouping is
# in the `openapi.yaml` file.
'/start':
get:
responses:
"200":
description: OK
By doing this separation you can independently test each file or the whole API as a group.
There may be points where you repeat yourself, but by doing this you limit the chance of breaking changes to other API endpoints when using a "common" library.
However, you should still have a common definition library for some things such as:
errors
security
There is a limitation on this approach and that's the "Discriminators" (it may be a ReDoc issue though, but if you had types that have discriminators outside of the openapi.yaml ReDoc fails to render correctly.

See this answer for details on how to split your Swagger documentation across many files. This is done using JSON, but the same concept can apply to RAML.
EDIT: Adding content of link here
The basic structure of your Swagger JSON should look something like this:
{
"swagger": "2.0",
"info": {
"title": "",
"version": "version number here"
},
"basePath": "/",
"host": "host goes here",
"schemes": [
"http"
],
"produces": [
"application/json"
],
"paths": {},
"definitions": {}
}
The paths and definitions are where you need to insert the paths that your API supports and the model definitions describing your response objects. You can populate these objects dynamically. One way of doing this could be to have a separate file for each entity's paths and models.
Let's say one of the objects in your API is a "car".
Path:
{
"paths": {
"/cars": {
"get": {
"tags": [
"Car"
],
"summary": "Get all cars",
"description": "Returns all of the cars.",
"responses": {
"200": {
"description": "An array of cars",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/car"
}
}
},
"404": {
"description": "error fetching cars",
"schema": {
"$ref": "#/definitions/error"
}
}
}
}
}
}
Model:
{
"car": {
"properties": {
"_id": {
"type": "string",
"description": "car unique identifier"
},
"make": {
"type": "string",
"description": "Make of the car"
},
"model":{
"type": "string",
"description": "Model of the car."
}
}
}
}
You could then put each of these in their own files. When you start your server, you could grab these two JSON objects, and append them to the appropriate object in your base swagger object (either paths or definitions) and serve that base object as your Swagger JSON object.
You could also further optimize this by only doing the appending once when the server is started (since the API documentation will not change while the server is running). Then, when when the "serve Swagger docs" endpoint is hit, you can just return the cached Swagger JSON object that you created when the server was started.
The "serve Swagger docs" endpoint can be intercepted by catching a request to /api-docs like below:
app.get('/api-docs', function(req, res) {
// return the created Swagger JSON object here
});

You can use $ref but not have good flexibility, I suggest you process YAML with an external tool like 'Yamlinc' that mix multiple files into one using '$include' tag.
read more: https://github.com/javanile/yamlinc

Related

Can you use separate files for json subschemas?

I am new to using JSON schemas and I am pretty confused about subschemas. I have done many searches and read https://json-schema.org/understanding-json-schema/structuring.html but I feel like I am not getting some basic concepts.
I'd like to break up a schema into several files. For instance, I have a metric schema that I would like nested in a category schema. Can a subschema be a separate file that is referenced or is it a block of code in the same file as the base schema? If they are separate files, how do you reference the other file? I have tried using a lot of various values for $ref with the $id of the nested file but it doesn't seem to work.
I don't think I really understand the $id and $schema fields. I have read the docs on them but leave still feeling confused. Does the $id need to be a valid URI? The docs seem to say that they don't. And I just copied the $schema value from the jsonschema site examples.
Any help would be appreciated about what I am doing wrong.
(added the following after Ether's reply)
The error messages I get are:
KeyError: 'http://mtm/metric'
and variations on
jsonschema.exceptions.RefResolutionError: HTTPConnectionPool(host='mtm', port=80): Max retries exceeded with url: /metric (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe9204a31c0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))
Here is the category schema in category_schema.json:
{
"$id": "http://mtm/category",
"$schema":"https://json-schema.org/draft/2020-12/schema",
"title":"Category Schema",
"type":"object",
"required":["category_name", "metrics"],
"properties": {
"category_name":{
"description": "The name of the category.",
"type":"string"
},
"metrics":{
"description": "The list of metrics for this category.",
"type":"array",
"items": {
"$ref": "/metric"
}
}
}
}
And here is the metric schema in metric_schema.json:
{
"$id": "http://mtm/metric",
"$schema":"https://json-schema.org/draft/2020-12/schema",
"title":"Metric Schema",
"description":"Schema of metric data.",
"type":"object",
"required": ["metric_name"],
"properties": {
"metric_name":{
"description": "The name of the metric in standard English. e.g. Live Views (Millions)",
"type":"string"
},
"metric_format": {
"description": "The format of the metric value. Can be one of: whole, decimal, percent, or text",
"type": "string",
"enum": ["integer", "decimal", "percent", "text"]
}
}
}
Yes, you can reference schemas in other documents, but the URIs need to be correct, and you need to add the files manually to the evaluator if they are not network- or filesystem-available.
In your first schema, you declare its uri is "http://mtm/category". But then you say "$ref": "/mtm/metric" -- since that's not absolute, the $id URI will be used as a base to resolve it. The full URI resolves to "http://mtm/mtm/metric", which is not the same as the identifier used in the second schema, so the document won't be found. This should be indicated in the error message (which you didn't provide).

Where is id: { type: 'ID' } generated in in the featherjs models created by feathers-plus cli defined in the official jsonschema?

I have looked at the json schema docs and examples and do not see a type of ID as created in the json models by the generator. Example feathers-plus cli jsonschema
properties: {
// !code: schema_properties
id: { type: 'ID' },
email: {},
In the jsonschema official docs example id is defined like
"properties": {
"id": {
"type": ["string", "integer"],
This is not allowed by JSON Schema.
According to the docs at https://github.com/feathers-plus/generator-feathers-plus/tree/master/docs/json-schema
Feathers Models are based on JSON-schema.
This reads to me that their models are not quite JSON Schema.
If you want to know why, you should probably raise an issue on their github repo.

Validating correctness of $ref in json schema

The requirement is to validate given json schema that there are no dangling $ref pointing to the definitions within the file.
{
"$schema": "http://json-schema.org/draft-6/schema#",
"definitions": {
"date": {
"type": "string",
"pattern": "^(0?[1-9]|[12][0-9]|3[01])\\-(0?[1-9]|1[012])\\-\\d{4}$"
},
},
"properties": {
"my_date": {"$ref": "#/definitions/dat"}
}
}
Here, there is a typo in the reference (dat instead of date). I want to catch such instances rather than having a run time failure.
Library being used: https://github.com/java-json-tools/json-schema-validator
You could validate that the use of $ref resolves by digesting the JSON, recursivly extracting the value of $ref, splitting on slash, and checking the path exists.
This COULD get more complicated as you might have external references which target URLs.
I can't give you any code as I don't know JAVA. It doesn't seem like what you want is specifically available using that library.

OpenShift Aggregated Logging: Parse Apache access log

When using OpenShift Aggregated Logging I get logs nicely fed into elasticsearch. However, the line as logged by apache ends up in a message field.
I'd like to create queries in Kibana where I can access the url, the status code and other fields individually. For that the special apache access log parsing needs to be done.
How can I do that?
This is an example entry as seen in kibana:
{
"_index": "42-steinbruchsteiner-staging.3af0bedd-eebc-11e6-af4b-005056a62fa6.2017.03.29",
"_type": "fluentd",
"_id": "AVsY3aSK190OXhxv4GIF",
"_score": null,
"_source": {
"time": "2017-03-29T07:00:25.595959397Z",
"docker_container_id": "9f4fa85a626d2f5197f0028c05e8e42271db7a4c674cc145204b67b6578f3378",
"kubernetes_namespace_name": "42-steinbruchsteiner-staging",
"kubernetes_pod_id": "56c61b65-0b0e-11e7-82e9-005056a62fa6",
"kubernetes_pod_name": "php-app-3-weice",
"kubernetes_container_name": "php-app",
"kubernetes_labels_deployment": "php-app-3",
"kubernetes_labels_deploymentconfig": "php-app",
"kubernetes_labels_name": "php-app",
"kubernetes_host": "itsrv1564.esrv.local",
"kubernetes_namespace_id": "3af0bedd-eebc-11e6-af4b-005056a62fa6",
"hostname": "itsrv1564.esrv.local",
"message": "10.1.3.1 - - [29/Mar/2017:01:59:21 +0200] "GET /kwf/status/health HTTP/1.1" 200 2 "-" "Go-http-client/1.1"\n",
"version": "1.3.0"
},
"fields": {
"time": [
1490770825595
]
},
"sort": [
1490770825595
]
}
Disclaimer: I did not test this out in openshift. I don't know which tech stack you are using for your microservice.
This is how I do this in a spring boot application (with logback) deployed in Kubernetes.
1. Use logstash encoder for logback (This will write logs in Json format which is more ELK stack friendly)
I have a gradle dependency to enable this
compile "net.logstash.logback:logstash-logback-encoder:3.5"
Then configure LogstashEncoder as encoder in the appender, in logback-spring.groovy/logback-spring.xml (or logabck.xml)
2. Have some filters or libraries to write the access log
For 2. Either use
A. Use "net.rakugakibox.springbootext:spring-boot-ext-logback-access:1.6" library
(This is what I am using)
It gives in a nice json format, as follows
{
"#timestamp":"2017-03-29T09:43:09.536-05:00",
"#version":1,
"#message":"0:0:0:0:0:0:0:1 - - [2017-03-29T09:43:09.536-05:00] \"GET /orders/v1/items/42 HTTP/1.1\" 200 991",
"#fields.method":"GET",
"#fields.protocol":"HTTP/1.1",
"#fields.status_code":200,
"#fields.requested_url":"GET /orders/v1/items/42 HTTP/1.1",
"#fields.requested_uri":"/orders/v1/items/42",
"#fields.remote_host":"0:0:0:0:0:0:0:1",
"#fields.HOSTNAME":"0:0:0:0:0:0:0:1",
"#fields.content_length":991,
"#fields.elapsed_time":48,
"HOSTNAME":"ABCD"
}
OR
B. Use Logback's Tee Filter
OR
C. Spring's CommonsRequestLoggingFilter (Did not really test this out)
Add a bean definition
#Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
CommonsRequestLoggingFilter crlf = new CommonsRequestLoggingFilter();
crlf.setIncludeClientInfo(true);
crlf.setIncludeQueryString(true);
crlf.setIncludePayload(true);
return crlf;
}
Then set org.springframework.web.filter.CommonsRequestLoggingFilter to DEBUG, this can be done using the application.properties by adding:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG

Bigcommerce stencil what is customLayouts used for?

I noticed that after using the command stencil init to generate a .stencil file for a new stencil project, the generate file contains a customLayouts attribute. For example, the file might contain this:
{
"normalStoreUrl": "http://www.my-store.com",
"port": 3000,
"username": "Stencil",
"token": "11223344556677889900",
"customLayouts": {
"products": {},
"search": {},
"brands": {},
"categories": {}
}
}
Can someone please explain the purpose of this customLayout object and how it can be used?
It isn't presently in use. It will be available for use to have customized templates per each of those types of pages once we have finished some engineering work. It is a placeholder at this time.