Skip to content
代码片段 群组 项目
代码所有者
将用户和群组指定为特定文件更改的核准人。 了解更多。
api_styleguide.md 12.42 KiB
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments

API style guide

This style guide recommends best practices for API development.

Instance variables

Please do not use instance variables, there is no need for them (we don't need to access them as we do in Rails views), local variables are fine.

Entities

Always use an Entity to present the endpoint's payload.

Documentation

Each new or updated API endpoint must come with documentation, unless it is internal or behind a feature flag. The docs should be in the same merge request, or, if strictly necessary, in a follow-up with the same milestone as the original merge request.

See the Documentation Style Guide RESTful API page for details on documenting API resources in Markdown as well as in OpenAPI definition files.

Methods and parameters description

Every method must be described using the Grape DSL (see environments.rb for a good example):

  • desc for the method summary. You should pass it a block for additional details such as:

    • The GitLab version when the endpoint was added. If it is behind a feature flag, mention that instead: This feature is gated by the :feature_flag_symbol feature flag.
    • If the endpoint is deprecated, and if so, its planned removal date
  • params for the method parameters. This acts as description, validation, and coercion of the parameters

A good example is as follows:

desc 'Get all broadcast messages' do
  detail 'This feature was introduced in GitLab 8.12.'
  success Entities::BroadcastMessage
end
params do
  optional :page,     type: Integer, desc: 'Current page number'
  optional :per_page, type: Integer, desc: 'Number of messages per page'
end
get do
  messages = BroadcastMessage.all

  present paginate(messages), with: Entities::BroadcastMessage
end

Declared parameters

Grape allows you to access only the parameters that have been declared by your params block. It filters out the parameters that have been passed, but are not allowed.

https://github.com/ruby-grape/grape#declared

Exclude parameters from parent namespaces

By default declared(params)includes parameters that were defined in all parent namespaces.