Giter Club home page Giter Club logo

azure-api-style-guide's Introduction

Azure API Style Guide

This repository contains a Style Guide for OpenAPI definitions of Azure services. The Style Guide is a companion to the Azure API Guidelines, the OpenAPI 2.0 specification, and the OpenAPI 3.1 specification.

The repository also contains a Spectral ruleset to check an API definition for conformance to the Azure API Guidelines and this Style Guide.

NOTE: It is highly recommended that you leverage the Spectral rule set. Azure service teams have found Spectral to be very useful identifying many common mistakes that affect the overall quality of their Open API documentation. It's one of the first things the API Stewardship Board turns to when revieing an API specification.

However, the errors, warnings, and info messages identified by Spectral should be evaluated in the context of your service, and using your judgement. If you have any questions, concerns, or comments, please don't hesitate to start a discussion in the API Stewardship Teams Channel.

How to use the Spectral Ruleset

Dependencies

The Spectral Ruleset requires Node version 14 or later.

Install Spectral

npm i @stoplight/spectral-cli -g

Usage

You can specify the ruleset directly on the command line:

spectral lint -r https://raw.githubusercontent.com/azure/azure-api-style-guide/main/spectral.yaml <api definition file>

Or you can create a Spectral configuration file (.spectral.yaml) that references the ruleset:

extends:
  - https://raw.githubusercontent.com/azure/azure-api-style-guide/main/spectral.yaml

Example

spectral lint -r https://raw.githubusercontent.com/azure/azure-api-style-guide/main/spectral.yaml petstore.yaml

Using the Spectral VSCode extension

There is a Spectral VSCode extension that will run the Spectral linter on an open API definition file and show errors right within VSCode. You can use this ruleset with the Spectral VSCode extension.

  1. Install the Spectral VSCode extension from the extensions tab in VSCode.
  2. Create a Spectral configuration file (.spectral.yaml) in the root directory of your project as shown above.
  3. Set spectral.rulesetFile to the name of this configuration file in your VSCode settings.

Now when you open an API definition in this project, it should highlight lines with errors. You can also get a full list of problems in the file by opening the "Problems panel" with "View / Problems". In the Problems panel you can filter to show or hide errors, warnings, or infos.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

azure-api-style-guide's People

Contributors

dependabot[bot] avatar jeremyfiel avatar jjwedemyer avatar josefree avatar markweitzel avatar microsoft-github-operations[bot] avatar microsoftopensource avatar mikekistler avatar mushmal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azure-api-style-guide's Issues

Add a rule to check for valid / recommended media types

Most Azure services simply accept and return "application/json" bodies, and this is the recommended design (except for PATCH, which should be "application/merge-patch+json".

A few other media types are common and generally acceptable:

  • "application/octet-stream", "text/plain", "text/csv"
  • "multipart/form-data" when used alone (see below)

But there are cases where services define invalid content types or use valid types in a way that is not recommended:

  • "" can only be used for the type or subtype -- not as a wildcard character. So "application/+json" is invalid (according to the BNF in RFC 6838) -- this comes from appconfiguration.json.
  • "multipart/form-data" with any other content type. This is a problem because OAS2 does not allow both "form" and "body" parameters on a single operation.
  • "text/json" -- commonly seen with "application/json". These are essentially the same thing, so no need to have both of them, especially in "produces"

We may want to decide on whether parameters should be allowed -- there are more than a few instances of ""application/json; charset=utf-8" in the current specs.

When to use minLength, maxLength, etc.

It's not helpful and potentially confusing to specify minLength, maxLength, etc on a string property/parameter that has more stringent validation properties. For example, a parameter or property that should contain an access token will be validated by AAD and determined to be valid or not. So we should recommend using minLength and maxLength only when there is not some more specific validation performed on the string.

Fix readOnly rule to handle OpenAPI 2 polymorphism pattern.

The readOnly rule categorizes schemas as "request" or "response" if they are reachable from an operation request or response body, respectively. But the current logic does not handle the OpenAPI 2 polymorphism pattern, where the parent schema does not reference child schemas directly -- instead, the child schema "allOf"s the parent into itself. As a result, the rule is generating false positives, such as in this PR.

Rules az-property-type is outdated

the rules az-property-type looks has been defined for OAS2

the condition below is now outdated
given: $..properties[?(@object() && @.$ref == undefined && @.allOf == undefined)]

since OAS 3 new keywords has been introduced like oneOf and anyOf
so the rules need to be amended to

 given: $..properties[?(@object() && @.$ref == undefined && ( @.allOf == undefined  && @.oneOf == undefined && @.anyOf == undefined ))]

thanks for your job @markweitzel

Rule for multipart/form-data

If an operation is defined to accept multipart/form-data but only defines a single formData parameter, flag this and recommend to change to application/octet-stream and with a body parameter.

Simpler names are better

Add a rule that checks schema names for throw-away words such as "response" and "payload" and recommends dropping those words. Might need to check if recommended name is already present -- to avoid recommending a duplicate.

We could add some exceptions, e.g. ErrorResponse, since this generally won't show up in method signatures in the SDKs.

`az-success-response-body` JSON path is invalid for OAS3

JSON path is not scoped to the field values of the response object in OAS3.
the first level is content
the second level can be any mime-type

$.paths[*][*].responses[?(@property >= 200 && @property < 300 && @property != 202  && @property != 204)].content[*]

Example:

{
    "openapi": "3.0.0",
    "paths": {
        "/endpoint": {
            "get": {
                "responses": {
                    "200": {
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/SuccessfulResponse"
                                }
                            }
                        },
                        "description": "Success"
                    }
                }
            }
        }
    }
}

az-unique-parameter-names only running on oas2

Hi,

Thanks for providing this great repository,
my Question: Is there a reasoning for az-unique-parameter-names only being applied to OAS2 specs?
I'm trying to build a ruleset which ensures API Specs are within limitations of the API Management import, within which all parameters need to be unique for OAS3 as well.

The az-lro-headers rule should be case-insensitive

The az-lro-headers rule that checks for a header named specifically "Operation-location" and issues a message when it is not present.

But the HTTP specification say that header names are case-insensitive, so "Operation-Location" and "operation-location" and even "oPERATION-lOCATION" should all be acceptable.

Check for custom "x-" headers

To enforce the guideline:

DO NOT use "x-" prefix for custom headers, unless the header already exists in production [RFC 6648].

Add rule to check repeatability headers

The Azure API guidelines recommend:

☑️ YOU SHOULD support repeatable requests according as defined in OASIS Repeatable Requests Version 1.0.

This involves adding two header parameters, Repeatability-Request-ID and Repeatability-First-Sent, to an operation definition. Recently a service team did this (at our recommendation) but made a few mistakes in doing so.

  • They specified x-ms-parameter-location: client on both parameters -- that is incorrect since the value of these headers should be set on each operation.
  • They did not specify format: date-time on Repeatability-First-Sent.

We may also want to recommend format: uuid on `

The API guidelines also state:

When [the repeatability header is] understood, all endpoints co-located behind a DNS name MUST understand the header.

This might be another thing to check for.

[bug] the rules az-property-type: gives false postive

given the rules az-property-type:

this generate false positive as it catches properties in examples .

use case beeing that i have an API with endpoints returning an object containing a field called
"properties" as part of the payload

for instance

examples:
 Dog:
      description: |
        Creation of a Zero Coupon scenario 
      value:
        type: GOOD_DOG
        properties:
          size: TALL
          legs:
            - id : 1

returns
warning az-property-type Property should have a defined type. components.examples.Dog.value.properties.legs

Add a rule to check that the schemas for all 2XX responses are the same

For client generation, we want to have only one type of object returned from an operation. In terms of the REST API, that means that all the success response codes (2XX) should have the same schema.

Comparing schemas for equality might be a little tricky, so we could simplify the logic somewhat:

  • An operation cannot return 200/201 and 204
  • We don't need to check 202 since az-lro-reponses-codes flags any 2XX for an operation that returns 202

Maybe we'll start with that.

`az-property-description` rule breaks on node js

Hi,
i'm encountering an error using this ruleset with the spectral cli executable, whilst everything is working in the VSCode extension.

in my node.js setup the program is exiting with 'undefined' is not defined where i've tracked down to the ?(@.$ref === undefined) expression on L174

In VSCode this rule seems to be running just fine, even showing all found issues with the OAS.

Add etag linting rule

Develop a linter rule that says that “if you have a property named etag, it should have format etag”. And probably that you shouldn’t have “etag” if the property name isn’t etag. And if you are a header named etag, I’d argue that we don’t need to specify format. But we could.

Some rules have broken for oas3 format

Some rules are not working for oas3 format API definitions.

  • az-api-version-enum
  • az-header-disallowed
  • az-parameter-default-not-allowed

Sadly there are no oas3 tests for any of these rules so it's unclear whether they ever worked.

In all three cases, the problem appears to be caused by the "filter" in the "given". It is unclear why these "given"s work for oas2 and not for oas3.

Update Style Guide to cover securityDefintions

The Style Guide should be updated with guidelines for documenting the security schemes supported/required by the API.

And we should add some Spectral rules to enforce these guidelines.

Fix test setup to handle @object() in given statements of yaml ruleset

The current linterForRule utility method attempts to construct a linter with just one rule enabled -- the rule under test. It uses the spectral ruleset migrator and logic "borrowed" from the Spectral CLI, which also does the conversion of yaml rulesets to the new "js" format. Unfortunately, the logic in linterForRule was simplified from the Spectral logic and does not seem to work with some features of JSONPath-Plus, in particular the @object() condition. We need to fix this going forward so that we can use these important features (and test them).

Issue "info" message for path parameter without a "pattern"

When a path parameter is a user-specified ID, it should be constrained to a specific set of characters.

YOU SHOULD restrict the characters allowed in user-specified path segments (i.e. path parameters values) to 0-9 A-Z a-z - . _ ~ (do not allow :).

Should also flag missing maxLength and maybe even minLength.

Add checks for LRO Guidelines

An operation that returns a 202 should not return any other success status code.

YOU SHOULD NOT return any other 2xx status code from the initial request of a status-monitor LRO -- return 202-Accepted and a status monitor URL even if processing was completed before the initiating request returns.

az-pagination-response must check allOf when looking for response schema properties

The pagination-response function currently only checks for the value and nextLink properties in the properties object of the response schema. But these properties could be defined in the children of an allOf in the response schema, so the code will need to nest down into the allOf to find the properties it is looking for.

And this will be complicated because it will also have to keep track of where it found those properties so it can set the paths correctly in any error messages that are issued.

Add rule to flag '/:' in path

We want services to use the new URL pattern for actions which has a bare ":" rather than "/:" preceding the action name.

Revisit typing guidance for parameters borrowed from OData

The Style Guide currently recommends that "orderby", "select", and "expand" be defined as an array of strings.

https://github.com/Azure/azure-api-style-guide/blob/main/openapi-style-guide.md#support-for-pagination

This might be inconsistent with the current practice in Azure, as many services appear to define these simply as type: string.

We need to re-evaluate this guidance to make sure we do not inadvertently create more inconsistency.

`az-error-response` requires certain read-only properties to be marked as "required"

As per the Guidelines, the ErrorResponse object must have an "error" property, while the Error object must have "code" and "message" properties. The az-error-response rule requires that these properties are marked as "required" in the swagger spec. However, my understanding is that all these properties must be marked as "readOnly", since they are only ever used in responses, and because of this, they cannot be simultaneously marked as "required" as per the OpenAPI specification 2.0.

Possible style guide rule for additionalProperties

The JSON schema additionalProperties is a potential source of confusion and error. Restricting its use to very specific applications might be a good style.

One possible restriction is to only allow additionalProperties when not a sibling of properties -- which is just a way of defining a map. This is a very common pattern in Azure:

        "tags": {
          "type": "object",
          "additionalProperties": {
            "type": "string"
          },
          "description": "Application specific metadata in the form of key-value pairs."
        }

Some rules not working correctly in VS Code extension

There are a few rules -- in particular the ones that use "advanced" JSON Path features -- that are not currently working in the VSCode extension because that extension has not been updated to use Spectral 6.0. Some specific rules that are not working correctly are:

  • az-additional-properties-and-properties
  • az-lro-extension

The rules do work correctly from the CLI.

It looks like there is an effort to get the Spectral VSCode plugin updated to v6:

stoplightio/vscode-spectral#107

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.