我有一个表单,要求用户输入他们的 api 详细信息。结果可以导出为 csv、excel 或纯文本。
是否有任何工具、脚本、库可以根据结果生成 openapi 规范?
是的,有多种方法和工具可以将 CSV 数据转换为 OpenAPI 规范。以下是使用 Python 和自定义脚本的一个选项:
import pandas as pd
import yaml
import json
def csv_to_openapi(csv_file, api_name, version="1.0.0"):
# Read CSV file
df = pd.read_csv(csv_file)
# Create basic OpenAPI structure
openapi_spec = {
"openapi": "3.0.0",
"info": {
"title": api_name,
"version": version
},
"paths": {},
"components": {
"schemas": {}
}
}
# Create schema from CSV columns
properties = {}
for column in df.columns:
# Infer data type from column
dtype = str(df[column].dtype)
if dtype.startswith('int'):
type_name = 'integer'
elif dtype.startswith('float'):
type_name = 'number'
elif dtype == 'bool':
type_name = 'boolean'
else:
type_name = 'string'
properties[column] = {"type": type_name}
# Add schema
schema_name = f"{api_name}Schema"
openapi_spec["components"]["schemas"][schema_name] = {
"type": "object",
"properties": properties
}
# Add basic CRUD paths
resource_path = f"/{api_name.lower()}"
openapi_spec["paths"][resource_path] = {
"get": {
"summary": f"Get all {api_name} records",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": f"#/components/schemas/{schema_name}"
}
}
}
}
}
}
},
"post": {
"summary": f"Create new {api_name} record",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": f"#/components/schemas/{schema_name}"
}
}
}
},
"responses": {
"201": {
"description": "Successfully created"
}
}
}
}
return openapi_spec
# Usage example
spec = csv_to_openapi("your_data.csv", "YourAPI")
# Save as YAML
with open('openapi-spec.yaml', 'w') as f:
yaml.dump(spec, f, sort_keys=Fal`enter code here`se)
# Save as JSON
with open('openapi-spec.json', 'w') as f:
json.dump(spec, f, indent=2)