Skip to content

feat(cli): add 'fern export' command #7586

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions fern/pages/changelogs/cli/2025-06-23.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 0.64.16
**`(feat):`** Add `fern export` command to export API to an OpenAPI spec.


27 changes: 25 additions & 2 deletions fern/pages/cli-api/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: 'Commands'
description: 'Complete reference for all Fern CLI commands for generating SDKs and developer documentation.'
subtitle: 'Learn about the Fern CLI commands.'
hideOnThisPage: true
max-toc-depth: 3
---

| Command | Description |
Expand All @@ -18,14 +18,15 @@ hideOnThisPage: true
| [`fern docs dev`](#fern-docs-dev) | Run local documentation preview server |
| [`fern generate --docs`](#fern-generate---docs) | Build & publish documentation updates |

## SDK Generation Commands
## Generation Commands

| Command | Description |
| --------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [`fern generate`](#fern-generate) | Build & publish SDK updates |
| [`fern write-definition`](#fern-write-definition) | Convert OpenAPI specifications to [Fern Definition](/learn/api-definition/fern/overview) |
| [`fern write-overrides`](#fern-write-overrides) | Create OpenAPI customizations |
| [`fern generator upgrade`](#fern-generator-upgrade) | Update SDK generators to latest versions |
| [`fern export`](#fern-export) | Export an OpenAPI spec for your API |

## Detailed Command Documentation

Expand Down Expand Up @@ -491,3 +492,25 @@ Use `--group` to upgrade generators within a specific group in your `generators.
fern generator upgrade --group public
```

### `fern export`

Use `fern export` to generate an OpenAPI spec for your API.

<Callout intent='info'>
Generally, this is only useful if you're defining your API in another format,
like the [Fern Definition](/learn/api-definition/fern/overview).
</Callout>

<CodeBlock title="terminal">
```bash
fern export [--api <api>] <path>
```
</CodeBlock>

#### `--api`

Use `--api` to specify the API to write the OpenAPI for if you have multiple defined in your `fern/apis/` folder.

```bash
fern export --api public-api path/to/openapi.yml
```
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,7 @@ export class ExampleConverter extends AbstractConverter<AbstractConverterContext
{ type: "object" },
{ type: "array" }
]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);

// Find properties in the example that are not defined in the schema
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@types/lodash-es": "^4.17.12",
"@types/semver": "^7.5.8",
"@types/tar": "^6.1.11",
"@types/url-join": "4.0.1",
"@types/validate-npm-package-name": "^4.0.0",
"@types/yargs": "^17.0.28",
"ansi-escapes": "^5.0.0",
Expand All @@ -106,11 +107,13 @@
"latest-version": "^9.0.0",
"lodash-es": "^4.17.21",
"ora": "^7.0.1",
"openapi-types": "^12.1.3",
"semver": "^7.6.2",
"tar": "^6.2.1",
"tmp-promise": "^3.0.3",
"tsup": "^8.3.5",
"undici": "^6.21.1",
"url-join": "^5.0.0",
"validate-npm-package-name": "^5.0.1",
"yaml": "^2.4.5",
"yargs": "^17.4.1",
Expand Down
37 changes: 37 additions & 0 deletions packages/cli/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { addGeneratorCommands, addGetOrganizationCommand } from "./cliV2";
import { addGeneratorToWorkspaces } from "./commands/add-generator/addGeneratorToWorkspaces";
import { diff } from "./commands/diff/diff";
import { previewDocsWorkspace } from "./commands/docs-dev/devDocsWorkspace";
import { generateOpenAPIForWorkspaces } from "./commands/export/generateOpenAPIForWorkspaces";
import { formatWorkspaces } from "./commands/format/formatWorkspaces";
import { generateDynamicIrForWorkspaces } from "./commands/generate-dynamic-ir/generateDynamicIrForWorkspaces";
import { generateFdrApiDefinitionForWorkspaces } from "./commands/generate-fdr/generateFdrApiDefinitionForWorkspaces";
Expand Down Expand Up @@ -182,6 +183,7 @@ async function tryRunCli(cliContext: CliContext) {
});
addGenerateJsonschemaCommand(cli, cliContext);
addWriteDocsDefinitionCommand(cli, cliContext);
addExportCommand(cli, cliContext);

// CLI V2 Sanctioned Commands
addGetOrganizationCommand(cli, cliContext);
Expand Down Expand Up @@ -1340,3 +1342,38 @@ function addWriteDocsDefinitionCommand(cli: Argv<GlobalCliOptions>, cliContext:
}
);
}

function addExportCommand(cli: Argv<GlobalCliOptions>, cliContext: CliContext) {
cli.command(
"export <output-path>",
"Export your API to an OpenAPI spec",
(yargs) =>
yargs
.positional("output-path", {
type: "string",
description: "Path to write the OpenAPI spec",
demandOption: true
})
.option("api", {
string: true,
description: "Only run the command on the provided API"
}),
async (argv) => {
await cliContext.instrumentPostHogEvent({
command: "fern export",
properties: {
outputPath: argv.outputPath
}
});

await generateOpenAPIForWorkspaces({
project: await loadProjectAndRegisterWorkspacesWithContext(cliContext, {
commandLineApiWorkspace: argv.api,
defaultToAllApiWorkspaces: false
}),
cliContext,
outputPath: resolve(cwd(), argv.outputPath)
});
}
);
}
103 changes: 103 additions & 0 deletions packages/cli/cli/src/commands/export/convertIrToOpenApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { OpenAPIV3 } from "openapi-types";

import {
DeclaredErrorName,
DeclaredTypeName,
ErrorDeclaration,
IntermediateRepresentation,
TypeDeclaration
} from "@fern-api/ir-sdk";

import { convertServices } from "./converters/servicesConverter";
import { convertType } from "./converters/typeConverter";
import { constructEndpointSecurity, constructSecuritySchemes } from "./security";

export type Mode = "stoplight" | "openapi";

export function convertIrToOpenApi({
apiName,
ir,
mode
}: {
apiName: string;
ir: IntermediateRepresentation;
mode: Mode;
}): OpenAPIV3.Document | undefined {
const schemas: Record<string, OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject> = {};

const typesByName: Record<string, TypeDeclaration> = {};
Object.values(ir.types).forEach((typeDeclaration) => {
// convert type to open api schema
const convertedType = convertType(typeDeclaration, ir);
schemas[convertedType.schemaName] = {
title: convertedType.schemaName,
...convertedType.openApiSchema
};
// populates typesByName map
typesByName[getDeclaredTypeNameKey(typeDeclaration.name)] = typeDeclaration;
});

const errorsByName: Record<string, ErrorDeclaration> = {};
Object.values(ir.errors).forEach((errorDeclaration) => {
errorsByName[getErrorTypeNameKey(errorDeclaration.name)] = errorDeclaration;
});

const security = constructEndpointSecurity(ir.auth);

const paths = convertServices({
ir,
httpServices: Object.values(ir.services),
typesByName,
errorsByName,
errorDiscriminationStrategy: ir.errorDiscriminationStrategy,
security,
environments: ir.environments ?? undefined,
mode
});

const info: OpenAPIV3.InfoObject = {
title: ir.apiDisplayName ?? apiName,
version: ""
};
if (ir.apiDocs != null) {
info.description = ir.apiDocs;
}

const openAPISpec: OpenAPIV3.Document = {
openapi: "3.0.1",
info,
paths,
components: {
schemas,
securitySchemes: constructSecuritySchemes(ir.auth)
}
};

if (ir.environments != null && ir.environments.environments.type === "singleBaseUrl") {
openAPISpec.servers = ir.environments.environments.environments.map((environment) => {
return {
url: environment.url,
description:
environment.docs != null
? `${environment.name.originalName} (${environment.docs})`
: environment.name.originalName
};
});
}

return openAPISpec;
}

export function getDeclaredTypeNameKey(declaredTypeName: DeclaredTypeName): string {
return [
...declaredTypeName.fernFilepath.allParts.map((part) => part.originalName),
declaredTypeName.name.originalName
].join("-");
}

export function getErrorTypeNameKey(declaredErrorName: DeclaredErrorName): string {
return [
...declaredErrorName.fernFilepath.allParts.map((part) => part.originalName),
declaredErrorName.name.originalName
].join("-");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { OpenAPIV3 } from "openapi-types";

import {
DeclaredTypeName,
ExampleInlinedRequestBodyProperty,
ExampleObjectProperty,
NameAndWireValue,
TypeReference
} from "@fern-api/ir-sdk";

import { OpenApiComponentSchema, convertTypeReference, getReferenceFromDeclaredTypeName } from "./typeConverter";

export interface ObjectProperty {
docs: string | undefined;
name: NameAndWireValue;
valueType: TypeReference;
example?: ExampleObjectProperty | ExampleInlinedRequestBodyProperty;
}

export function convertObject({
docs,
properties,
extensions
}: {
docs: string | undefined;
properties: ObjectProperty[];
extensions: DeclaredTypeName[];
}): OpenAPIV3.SchemaObject {
const convertedProperties: Record<string, OpenApiComponentSchema> = {};
const required: string[] = [];
properties.forEach((objectProperty) => {
const convertedObjectProperty = convertTypeReference(objectProperty.valueType);

let example: unknown = undefined;
if (objectProperty.example != null && objectProperty.valueType.type === "primitive") {
example = objectProperty.example.value.jsonExample;
} else if (
objectProperty.example != null &&
objectProperty.valueType.type === "container" &&
objectProperty.valueType.container.type === "list" &&
objectProperty.valueType.container.list.type === "primitive"
) {
example = objectProperty.example.value.jsonExample;
}

convertedProperties[objectProperty.name.wireValue] = {
...convertedObjectProperty,
description: objectProperty.docs ?? undefined,
example
};
const isOptionalProperty =
objectProperty.valueType.type === "container" && objectProperty.valueType.container.type === "optional";
if (!isOptionalProperty) {
required.push(objectProperty.name.wireValue);
}
});
const convertedSchemaObject: OpenAPIV3.SchemaObject = {
type: "object",
description: docs,
properties: convertedProperties
};
if (required.length > 0) {
convertedSchemaObject.required = required;
}
if (extensions.length > 0) {
convertedSchemaObject.allOf = extensions.map((declaredTypeName) => {
return {
$ref: getReferenceFromDeclaredTypeName(declaredTypeName)
};
});
}
return convertedSchemaObject;
}
Loading
Loading