1

I would like to define two components: one for a single student and one for an array of students. But I want to follow the DRY principle. So I tried this:

components:
  schemas:
    student:
      type: object
      properties:
        StudentID:
          type: integer
          example: 3
        StudentName:
          type: string
          example: David
        StudentRemarks:
          type: string
          example: High Grade Student
    students:
      type: array
      items:
        $ref: '#/components/schemas/student/properties'

But it does not seem to work. Swaggers editor renders it this way:

Swagger editor showing referenced properties.

If I repeat myself:

components:
  schemas:
    student:
      type: object
      properties:
        StudentID:
          type: integer
          example: 3
        StudentName:
          type: string
          example: David
        StudentRemarks:
          type: string
          example: High Grade Student
    students:
      type: array
      items:
        properties:
          StudentID:
            type: integer
            example: 3
          StudentName:
            type: string
            example: David
          StudentRemarks:
            type: string
            example: High Grade Student

It looks this way:

Swagger editor showing repeated properties.

When I try to define a named anchor, I get the following error:

Structural error at components.schemas.student
should NOT have additional properties
additionalProperty: $id

How to reference another component correctly?

1 Answer 1

4

Your $ref goes one level too deep. You need to point to a schema (or subschema) not the properties object within a schema.

    students:
      type: array
      items:
        $ref: '#/components/schemas/student'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.