0

Is there a Python 3 package or code snippet that can read an OpenAPI 3 YAML file and convert it to a Python dictionary?

This is an example of the contents in an OpenAPI 3 YAML file

openapi: 3.0.0
servers:
    url: https://localhost/api
paths:
  /user/{userId}:
    get:
      summary: Get a user by ID
      parameters:
        - in: path
          name: userId
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          $ref: '#/components/schemas/UserFullName'
        age:
          type: integer
    UserFullName:
      type: object
      properties:
        firstName:
          type: string
        lastName:
          type: string

I want the package/code to generate a Python dictionary looking something like this

{
  "/user/{userId}": {
    "get": {
      "200": {
        "id": "integer",
        "name": {
          "firstName": "string",
          "lastName": "string"
        }
        "age" "integer"
      }
    }
  }
}

------ Edit -----

I have tried PyYaml, however, it is not returning what I am expecting.

I am expecting the '$ref' key-value pair to act as a string interpolation like this:

{
   "id":0,
   "name":{
      "firstName":"string",
      "lastName":"string"
   },
   "age":0
}

Instead, PyYaml is returning this:

{
  "id":0,
  "name": {
    "$ref": "#/components/schemas/UserFullName"
  },
  "age":0
}

1 Answer 1

0

Yes, there is a package called pyyaml. To know more please refer to this article How to Read YAML File to Dict in Python

1
  • Thank you, I have added clarification to the question after using PyYaml Oct 17, 2021 at 17:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.