AgID (Agenzia per l'Italia Digitale) · API Governance Rules
AgID (Agenzia per l'Italia Digitale) API Rules
Spectral linting rules defining API design standards and conventions for AgID (Agenzia per l'Italia Digitale).
50 Rules
error 23
warn 12
info 4
Published by AgID (Agenzia per l'Italia Digitale)
Served by the provider at https://github.com/teamdigitale/dati-semantic-schema-editor/blob/80bf9d6cfd2dc9b146401e990972a2a0d1943198/.spectral/rulesets/.openapirc.yml; the copy below was fetched from there.
Rule Categories
allowed
cache
has
hint
http
integer
missing
no
number
oas3
patch
paths
ratelimit
request
response
schema
sec
servers
use
Rules
warn
cache-control-parameter-undocumented
Cache usage SHOULD be extensively detailed in the `description` property to avoid data leaks or the usage of stale data. This rule should ensure in some way that the api provider documented extensively the cache usage to avoid data leaks or usage of stale data. The `no-transform` directive can be used in responses to avoid transforming proxies to modify (eg. compress) the content. For now this ruleset tests: * the presence of following keywords in the `description`: `max-age`, `private`, `no-store`, `no-cache`, `no-transform`. * that one and only one between Expires and Cache-Control is used. `Cache-Control` and `Expires` should not be used in conjunction, because `Cache-Control` overrides `Expires` when `max-age` is set. Instead if neither `Cache-Control` or `Expires` are set, clients MAY use heuristic cache like described in RFC7234.
$..[parameters][?(@ && @.in == "header" && @.name && @.name.match && @.name.match(/Cache-Control/i))]
info
cache-responses-undocumented
Cache usage SHOULD be extensively detailed in the `description` property to avoid data leaks or the usage of stale data. This rule should ensure in some way that the api provider documented extensively the cache usage to avoid data leaks or usage of stale data. The `no-transform` directive can be used in responses to avoid transforming proxies to modify (eg. compress) the content. For now this ruleset tests: * the presence of following keywords in the `description`: `max-age`, `private`, `no-store`, `no-cache`, `no-transform`. * that one and only one between Expires and Cache-Control is used. `Cache-Control` and `Expires` should not be used in conjunction, because `Cache-Control` overrides `Expires` when `max-age` is set. Instead if neither `Cache-Control` or `Expires` are set, clients MAY use heuristic cache like described in RFC7234.
$..[responses][?(@property[0] == "2" )][headers].[?(@property && @property.match && @property.match(/Cache-Control|Expires/i))]
info
cache-responses-indeterminate-behavior
Cache usage SHOULD be extensively detailed in the `description` property to avoid data leaks or the usage of stale data. This rule should ensure in some way that the api provider documented extensively the cache usage to avoid data leaks or usage of stale data. The `no-transform` directive can be used in responses to avoid transforming proxies to modify (eg. compress) the content. For now this ruleset tests: * the presence of following keywords in the `description`: `max-age`, `private`, `no-store`, `no-cache`, `no-transform`. * that one and only one between Expires and Cache-Control is used. `Cache-Control` and `Expires` should not be used in conjunction, because `Cache-Control` overrides `Expires` when `max-age` is set. Instead if neither `Cache-Control` or `Expires` are set, clients MAY use heuristic cache like described in RFC7234.
$..[responses][?(@property[0] == "2" )][headers]
warn
paths-kebab-case
Paths should be kebab-case (e.g. `path-parameter`). See Italian recommendation RAC_REST_NAME_002.
$.paths[*]
hint
request-headers-train-case
Headers should be Train-Case / HTTP-Header-Case (e.g. `X-Header-Name`). See Italian recommendation RAC_REST_NAME_003.
$..[parameters][?(@ && @.in=="header")].name
hint
response-headers-train-case
Headers should be Train-Case / HTTP-Header-Case (e.g. `X-Header-Name`). See Italian recommendation RAC_REST_NAME_003.
$..[responses][*].headers.*~
hint
schema-camel-case
Schema definitions should be CamelCase (pascal case with blank separator char). This improves readability and avoid confusion between schema names and properties. ``` Website: type: string format: url Person: type: object properties: website: $ref: "#/components/schemas/Website" ```
$.components.schemas[*]
error
no-forbidden-headers
OAS do not allow using the following HTTP headers in a specification file: Authorization, Content-Type and Accept. You MUST use the associate functionalities provided by OAS, instead.
$..parameters[?(@ && @.in == 'header')].name$..[responses][*].headers.*~
warn
no-x-headers-request
'HTTP' headers SHOULD NOT start with 'X-' RFC6648.
$..parameters[?(@ && @.in == 'header')].name
warn
no-x-headers-response
'HTTP' headers SHOULD NOT start with 'X-' RFC6648.
$..[responses][*].headers.*~
error
http-request-GET-no-body
A `GET` request MUST NOT accept a `requestBody` because this behavior is not interoperable. Moreover intermediaries such as reverse proxies are allowed to strip the content from `GET` requests. See RFC7231 for further information.
$.paths..get.requestBody
warn
http-request-DELETE-no-body
Sending a `requestBody` in a `DELETE` request is not considered interoperable. Moreover intermediaries such as reverse proxies might strip the content from `DELETE` requests. See RFC7231 for further information.
$.paths..delete.requestBody
error
http-response-no-content-204-205
Responses with the following status codes usually expected to include a content, which might have zero length: 200, 201, 202, 203, 206. Responses with status code 204 and 205 MUST NOT include a content. See RFC7231 for further information.
$..paths..responses[?(@property && @property.match("(204|205)") )]
hint
http-response-content-2xx
Responses with the following status codes usually expected to include a content, which might have zero length: 200, 201, 202, 203, 206. Responses with status code 204 and 205 MUST NOT include a content. See RFC7231 for further information.
$..paths..responses[?( @property && @property.match("(200|201|202|203|206)") )]
error
servers-description
Servers must have a description.
$.servers[*]$.paths..servers[*]
error
servers-use-https
Servers must use https to ensure the origin of the responses and protect the integrity and the confidentiality of the communication. You can use `http://` only on sandboxes environment. Use `x-sandbox: true` to skip this kind of check.
$.servers[?(@ && @["x-sandbox"] != true)].url$.paths..servers[?(@ && @["x-sandbox"] != true)].url
error
has-x-summary
The `#/info/x-summary` can be used to specify a brief, one-liner description of your API: this is very useful for catalog purposes (eg. this can be shown as your API subtitle in catalogs and developer portals). In OAS3.1 you can use the standard `#/info/summary` field.
$
warn
has-termsOfService
API SHOULD reference the URL of the Terms of Service in `#/info/termsOfService`
$
error
has-contact
API MUST reference a contact, either url or email in #/info/contact
$
hint
has-x-api-id
The `#/info/x-api-id` field can be used to associate an identifier to an API. This is useful to track an API even when its `#/info/title` changes.
$
error
use-semver
The API version field should follow [semantic versioning](https://semver.org/#semantic-versioning-specification-semver).
$.info.version
info
use-recommended-names-in-parameters
Use well defined parameter and schema names, deriving them from the national ontologies available at https://w3id.org/italia/onto/ For example, you can model a person using the following names: ``` { "en": { "given_name": "Mario", "family_name": "Rossi", "tax_code": "12345678901" }, "it": { "nome_proprio": "Mario", "cognome": "Rossi", "codice_fiscale": "12345678901" } } ```
$..parameters.[?(@ && @.name && @.name.match && @.name.match(/^(nome|name|surname|cf|fiscal_?code|fiscal_?number|first_?name|last_?name)$/i) )].name
info
use-recommended-names-in-schemas
Use well defined parameter and schema names, deriving them from the national ontologies available at https://w3id.org/italia/onto/
$..[?(@ && @.type=="object")].properties.[?( @property && @property.match && @property.match(/^(nome|name|surname|cf|fiscal_?code|fiscal_?number|first_?name|last_?name)$/i) )]
hint
no-method-name-in-operationId
Avoid using method names in `operationId`s because it couples the API design with the implementation. An operation that edits an entry can be published with different methods, for example either POST, PUT or PATCH, and while evolving the API you could decide to associate an operationId with another method. You can use for example ``` openapi: 3.0.1 ... paths: /entries: get: operationId: list_entries post: operationId: create_entry /entries/{id}: put: operationId: upsert_entry patch: operationId: edit_entry ```
$..[?(@ && @.operationId && @.operationId.match && @.operationId.match(/^(get|post|put|delete|patch|head)/i) )].operationId
error
number-format
Schema of type number or integer must specify a format to express the associated datatype, eg. `int32`, `int64`, ... You can express similar requirements using the `minimum` and `maximum` properties. See recommendation RAC_REST_FORMAT_004.
$..[?(@ && @.type=="number")]
error
integer-format
Schema of type number or integer must specify a format to express the associated datatype, eg. `int32`, `int64`, ... You can express similar requirements using the `minimum` and `maximum` properties. See recommendation RAC_REST_FORMAT_004.
$..[?(@ && @.type=="integer")]
hint
allowed-integer-format
To improve interoperability, integer and number formats are constrained to a shared subset. See recommendation RAC_REST_FORMAT_004.
$..[?(@ && @.type=="integer")].format
hint
allowed-number-format
To improve interoperability, integer and number formats are constrained to a shared subset. See recommendation RAC_REST_FORMAT_004.
$..[?(@ && @.type=="number")].format
error
no-swagger-2
Swagger 2 files are not allowed. Use OpenAPI >= 3.0
$
error
oas3-valid-media-example
Ensure examples are valid against their schema.
$
error
sec-securitySchemes-oauth-http
OAuth2 endpoints must use `https://`
$..[securitySchemes][?(@ && @.type=="oauth2")][*].[?(@property && @property.match(/Url$/i))]
error
sec-securitySchemes-oauth-allowed-flows
The OAuth2 authorization framework defines various [grant types](https://tools.ietf.org/html/rfc6749#section-1.3), most notably the [AuthorizationCode](https://tools.ietf.org/html/rfc6749#section-1.3.1) and the [Client Credentials](https://tools.ietf.org/html/rfc6749#section-1.3.4). Some grant types are now considered insecure and MUST not be used, including `implicit` and `password`. The new [OAuth2.1](https://tools.ietf.org/html/draft-ietf-oauth-v2-1-01) still in draft, removes them and suggests to replace the `implicit` with `authorizationCode` + PKCE defined in RFC7636. For further info, see the OAuth2 section of [API Security Guidelines](https://docs.italia.it/AgID/documenti-in-consultazione/lg-sicurezza-interoperabilita-docs/).
$..[?(@ && @.type=="oauth2")].flows
error
patch-media-type
The PATCH specification explicits that the request body contains a "patch document" describing the changes to be applied to the target resource. To avoid confusion, [this errata](https://www.rfc-editor.org/errata/eid3169) explains that `application/json` is not an appropriate media-type for `PATCH`. A correct example of PATCH using eg. `application/json-patch+json` media-type defined in RFC6902. ``` paths: /books/{book_id}: patch: requestBody: content: application/json-patch+json: schema: type: array ... example: [{ "op": "add", "path": "/baz", "value": "qux" }] ```
$..[patch][requestBody][content]
error
patch-without-request-body
The PATCH method requests that a set of changes described in the `requestBody` be applied to the target resource. A PATCH specification without a `requestBody` just applies no changes to the target resource. Since PATCH has impacts on caches, using it on a different target resource may result in non-interoperable behavior. For example, to modify the resource at `/user/123`, you can use the following PATCH request: ``` PATCH /user/123 Content-Type: application/json-patch+json [{"op": "replace", "path": "enable", "value": true}] ``` or POST request with the semantic implied by the target url: ``` POST /user/123/enable ``` Instead, the following request is expected to modify the `/user/123/enable` subresource, and not the `/user/123` one. ``` PATCH /user/123/enable ````
$.paths.*.patch
warn
patch-json-patch-mediatype
A correct example of PATCH using eg. `application/json-patch+json` media-type defined in RFC6902. ``` paths: /books/{book_id}: patch: requestBody: content: application/json-patch+json: schema: type: array ... example: [{ "op": "add", "path": "/baz", "value": "qux" }] ```
$..[patch][requestBody][content][application/json-patch+json][schema]
error
paths-status
You must define a `/status` path that can be used to health-check the API. Using this path avoids the arbitrary usage of a server URL for health-check scope. The `/status` endpoint should return: - a `application/json` or `application/problem+json` response with 200 OK when the service is up. - a `application/problem+json` response with 503 Service Unavailable when the service is down. The service provider is free to define the implementation logic for this path.
$.paths
error
paths-status-return-json
The "/status" endpoint must return "application/json" or "application/problem+json" when the service is Up.
$.paths.'/status'.get.responses.200.content.*~
error
paths-status-return-problem
The "/status" endpoint must return "application/problem+json" for all 4xx and 5xx error responses (Down state).
$.paths.'/status'.get.responses[?(@property.match(/^(4|5)/))].content.*~
warn
paths-status-problem-schema
The "/status" error response (4xx/5xx) must be a Problem object (RFC7807).
$.paths.'/status'.get.responses[?(@property.match(/^(4|5)/))].content.[schema]
hint
paths-http-method
When you design a REST API, you don't usually need to mention terms like `get`, `delete` and so on in your `paths`, because this information is conveyed by the HTTP method. Instead of using ``` POST /books/1234/delete HTTP/1.1 Host: api.example ``` You can simply call ``` DELETE /books/1234 HTTP/1.1 Host: api.example ``` Similarly you don't need verbs like `list` or `create` because the HTTP Semantics RFC7231 supports this kind of actions natively with proper methods and status code. Instead of ``` POST /create/user HTTP/1.1 Host: api.example Content-Type: application/json {"given_name": "Mario"} ``` You can use ``` POST /create/user HTTP/1.1 Host: api.example Content-Type: application/json {"given_name": "Mario"} ``` returning a proper response ``` HTTP/1.1 201 Created Location: /users/1234 ``` This simplifies securing your API as you know beforehand the kind of action which is going to be performed.
$.paths[?(@property && @property.match( "/(get|post|put|delete|patch)[\/A-Z_\-]?" ))]$.paths[?(@property && @property.match( "/(create|remove|list)[\/A-Z_\-]?" ))]
error
use-problem-json-for-errors
Error management is a key enabler of a resilient API ecosystem. Enforcing a consistent schema for errors between different APIs, enables client to properly implement an error management strategy, with positive impacts for users. Error responses should return one of the media-type defined in RFC7807: - `application/problem+json` - `application/problem+xml` An example of a valid response: ``` responses: "503": content: application/problem+json: schema: ... ```
$.paths.[*].responses[?(@property && @property.match(/^(4|5|default)/) && !@["x-noqa"] )].content.*~
hint
use-problem-schema
WARN: This rule is under implementation and just provides an hint. Error management is a key enabler of a resilient API ecosystem. Enforcing a consistent schema for errors between different APIs, enables client to properly implement an error management strategy, with positive impacts for users. This rule inspects the schema returned by an error response and verifies whether it contains the main properties defined in RFC7807: `status`, `title` and `detail`. An example of a valid payload is ``` { "title": "Not Found", "status": 404, "detail": "Book does not exist; id: 123" } ``` See recommendation RAC_REST_NAME_007.
$..[responses][?(@property && @property.match(/^(4|5|default)/) && !@["x-noqa"] )][schema].properties
hint
hint-problem-schema
WARN: This rule is under implementation and just provides an hint. Error management is a key enabler of a resilient API ecosystem. Enforcing a consistent schema for errors between different APIs, enables client to properly implement an error management strategy, with positive impacts for users. Errors should return RFC7807 objects. Instead, this schema seems to use non standard properties such as: `message`, `msg` and `code`. An error of the following form ``` { "msg": "Book with id: 123 does not exist.", "code": 6063 } ``` can be expressed in RFC7807 with ``` { "detail": "Book with id: 123 does not exist.", "type": "https://api.example/v1/errors/6063", "status": 404, "title": "Not Found" } ``` Returning an URI in `type`, instead of an opaque `code` can help the client in better identifying the error; moreover the URI though it should not be dereferenced automatically, can return an actual resource providing guidance in addressing the issue. See recommendation RAC_REST_NAME_007.
$..[responses][?(@property && @property.match(/^(4|5|default)/) && !@["x-noqa"] )][schema][properties].*~
warn
missing-retry-after
When a client is warned about a temporary server issue with a 503 status code, the server should explicitly communicate how long to wait before issuing further requests using the Retry-After header. Retry-After is defined in RFC7231.
$..[responses][?(@property == "503" )][headers]
warn
missing-ratelimit
Ratelimiting an API preserves a service and limits attack scenario [see API4:2019 Lack of Resources & Rate Limiting](https://owasp.org/www-project-api-security). APIs should use the following headers on successful and client error responses: - `X-RateLimit-Limit`: number of total requests in a give time window - `X-RateLimit-Remaining`: remaining requests in the current window - `X-RateLimit-Reset`: number of seconds before the window resets An example set of headers is the following ``` X-Ratelimit-Limit: 100 X-Ratelimit-Remaining: 40 X-Ratelimit-Reset: 12 ``` A standardization proposal for ratelimit headers is ongoing inside the IETF HTTPAPI Workgroup. See [the draft](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/)
$..[responses][?(@property[0] == "2" || (@property[0] == "4" && @property != "429"))][headers]
warn
ratelimit-429-presence
429 (Too Many Requests) responses must include either the `Retry-After` header or a complete set of RateLimit headers (`Limit`, `Remaining`, `Reset`).
$..[responses][?(@property == "429")][headers]
error
ratelimit-429-completeness
If RateLimit headers are provided for a 429 response, all three headers (Limit, Remaining, Reset) must be present and follow the same naming convention (standard or X- prefix). If both Retry-After and Reset are present, they should ideally represent the same time interval.
$..[responses][?(@property == "429")][headers && @ != null][?(@["X-RateLimit-Limit"] || @["X-RateLimit-Remaining"] || @["X-RateLimit-Reset"] || @["RateLimit-Limit"] || @["RateLimit-Remaining"] || @["RateLimit-Reset"])]
warn
response-with-json-object
JSON responses MUST use JSON objects, in order to be extensible. For example, instead of a list `[1, 2, 3]` you should return an object `{"items": [1, 2, 3]}`. This allows the schema to evolve in a backward compatible ways. There are notable exceptions when specific media types are involved, for example json-patch is an array (see RFC6902).
$..[responses][*][content][?(@property && @property.match("json$") && !@property.match(/json-patch\+json$/))][schema].type
error
sec-apikeys-url
API Keys are (usually opaque) strings that are passed in headers, cookies or query parameters to access APIs. Those keys can be eavesdropped, especially when they are stored in cookies or passed as URL parameters. ``` security: - ApiKey: [] paths: /books: {} /users: {} securitySchemes: ApiKey: type: apiKey in: cookie name: X-Api-Key ```
$..[securitySchemes][?(@ && @.type=="apiKey")].in
error
sec-credentials-parameters
URL parameters MUST NOT contain credentials such as apikey, password, or secret. See [RAC_GEN_004](https://docs.italia.it/italia/piano-triennale-ict/lg-modellointeroperabilita-docs/it/bozza/doc/04_Raccomandazioni%20di%20implementazione/04_raccomandazioni-tecniche-generali/01_globali.html?highlight=credenziali#rac-gen-004-non-passare-credenziali-o-dati-riservati-nellurl)
$..parameters[?(@ && @.in && @.in.match(/query|path/))].name
Spectral Ruleset
Work with this as data
Every ruleset here is available over the APIs.io API and to AI agents over MCP.