class Item:
def __init__(self, name: str, price: float, quantity: int):
self.name = name
self.price = price
self.quantity = quantity
def get_total_price(self) -> float:
return self.price * self.quantity
class -> OAS
Automatically generate OAS from python class implementation via OpenAI API
= Item("shoes", 49.0, 2)
item item.get_total_price()
98.0
= api.chat.completions.create(
res ="gpt-4o",
model=[
messages"role": "system", "content": "You are an assistant that generates OpenAPI specs."},
{"role": "user", "content": content}
{
]
)
= json.loads(res.json())['choices'][0]['message']['content']
res = res.replace("```yaml", "").replace("```", "").strip() res
#print(res)
# !pip install -qq pyyaml openapi-spec-validator
def validate_yaml(yaml_buffer):
try:
= yaml.safe_load(yaml_buffer)
yaml_content print("YAML syntax is valid.")
return yaml_content
except yaml.YAMLError as e:
print("YAML syntax error:", e)
return None
def validate_oas(yaml_content):
try:
validate_spec(yaml_content)print("OpenAPI specification format is valid.")
except Exception as e:
print("OpenAPI validation error:", e)
= validate_yaml(res)
yaml_content if yaml_content:
validate_oas(yaml_content)
YAML syntax is valid.
OpenAPI specification format is valid.
with open("oas.yaml", "w") as f:
yaml.dump(yaml_content, f)