# media-types-defined

Source: https://apigenie.pl/docs/linter/swagger/rules/media-types-defined

This rule checks whether the operations of a Swagger 2.0 document that send or
receive a body declare its media types.

## Rule Details

Swagger 2.0 declares the media types of request bodies with `consumes`, and
those of response bodies with `produces`. Both can be set on an operation or,
as defaults for all operations, on the root object. Without them, clients and
code generators have to guess the format of the payloads.

The `media-types-defined` rule reports:

- `Operation accepts a request body but defines no consumes` when an
  operation has a `body` or `formData` parameter, either its own or one
  inherited from its path item (references to `#/parameters` are resolved),
  and its effective `consumes` list is empty,
- `Operation returns a response body but defines no produces` when any
  response of an operation (references to `#/responses` are resolved) has a
  `schema`, and its effective `produces` list is empty.

An operation's own `consumes` or `produces` replaces the root one, as in the
specification, so an operation that sets `produces: []` has no response media
types even when the root object declares some.

## Configuration

None.

## Examples

**Good**. The root object declares the default media types.

```yaml
swagger: '2.0'
info:
  title: Pet Store
  version: 1.0.0
consumes: [application/json]
produces: [application/json]
paths:
  /pets:
    post:
      parameters:
        - name: pet
          in: body
          required: true
          schema:
            $ref: '#/definitions/Pet'
      responses:
        '201':
          description: The created pet.
          schema:
            $ref: '#/definitions/Pet'
definitions:
  Pet:
    type: object
    properties:
      name:
        type: string
```

**Bad**. The operation sends and receives a body, but no media types are
declared.

```yaml
swagger: '2.0'
info:
  title: Pet Store
  version: 1.0.0
paths:
  /pets:
    post:
      parameters:
        - name: pet
          in: body
          required: true
          schema:
            $ref: '#/definitions/Pet'
      responses:
        '201':
          description: The created pet.
          schema:
            $ref: '#/definitions/Pet'
definitions:
  Pet:
    type: object
    properties:
      name:
        type: string
```

## When Not to Use It

You may disable this rule if all consumers of your API assume a single media
type, such as `application/json`, without it being declared.

## Compatibility

This rule is compatible with Swagger 2.0 documents. OpenAPI 3.x documents
declare media types as the keys of `content` maps, so the OpenAPI linter has
no counterpart of this rule.
