Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Orval is a powerful tool for generating API clients from OpenAPI (Swagger) specifications. It helps streamline the process of creating and maintaining API clients by automating the generation of TypeScript or JavaScript code based on your API definitions.
Generate API Clients
This feature allows you to generate API clients from an OpenAPI specification file. You can specify the input file, output directory, and the HTTP client library (e.g., axios) to use.
const orval = require('orval');
orval.generate({
input: './path/to/openapi.yaml',
output: './path/to/output',
client: 'axios'
});
Custom Templates
Orval supports custom templates, allowing you to tailor the generated code to your specific needs. You can provide a path to your custom templates directory.
const orval = require('orval');
orval.generate({
input: './path/to/openapi.yaml',
output: './path/to/output',
client: 'axios',
templates: './path/to/custom/templates'
});
Mock Server
Orval can generate a mock server based on your OpenAPI specification. This is useful for testing and development purposes. You can specify the input file, output directory, and the port for the mock server.
const orval = require('orval');
orval.mock({
input: './path/to/openapi.yaml',
output: './path/to/output',
port: 3000
});
Swagger-js is a JavaScript library that allows you to interact with Swagger/OpenAPI documents. It provides tools for parsing and generating API clients, but it is less focused on TypeScript support and customization compared to Orval.
OpenAPI Generator is a comprehensive tool that supports generating API clients, server stubs, and API documentation from OpenAPI specifications. It offers a wide range of language and framework support, making it more versatile but also more complex to configure than Orval.
Swagger Codegen is another tool for generating API clients, server stubs, and API documentation from Swagger/OpenAPI definitions. It is similar to OpenAPI Generator but has a different set of templates and community support. Orval is more focused on TypeScript and modern JavaScript ecosystems.
orval
is able to generate axios client with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in yaml
or json
formats.
Type-safe data fetchers can be generated from an OpenAPI specification using the following command:
orval import --file MY_OPENAPI_SPEC.yaml --output my-awesome-generated-types.tsx
This command can be invoked by either:
orval
globally and running it in the terminal: npm i -g orval
, orscript
to your package.json
like so: "scripts": {
"start": "webpack-dev-server",
"build": "webpack -p",
+ "generate-fetcher": "orval import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx"
}
Your client can then be generated by running npm run generate-fetcher
. Optionally, we recommend linting/prettifying the output for readability like so:
"scripts": {
"start": "webpack-dev-server",
"build": "webpack -p",
"generate-fetcher": "orval import --file MY_SWAGGER_DOCS.json --output FETCHERS.tsx",
+ "postgenerate-fetcher": "prettier FETCHERS.d.tsx --write"
}
To enforce the best quality as possible of specification, we have integrated the amazing OpenAPI linter from IBM. We strongly encourage you to setup your custom rules with a .validaterc
file, you can find all useful information about this configuration here.
To activate this, add a --validation
flag to your orval
call.
Adding the --github
flag to orval import
instead of using the --file
flag allows us to create your client from an OpenAPI spec remotely hosted on GitHub. (how is this real life 🔥 )
To generate components from remote specifications, you'll need to follow the following steps:
Visit your GitHub settings.
Click Generate New Token and choose the following:
Token Description: (enter anything)
Scopes:
[X] repo
[X] repo:status
[X] repo_deployment
[X] public_repo
[X] repo:invite
Click Generate token.
Copy the generated string.
Open a terminal and run orval import --github username:repo:branch:path/to/openapi.yaml --output MY_FETCHERS.tsx
, substituting things where necessary.
You will be prompted for a token.
Paste your token.
You will be asked if you'd like to save it for later. This is entirely up to you and completely safe: it is saved in your node_modules
folder and not committed to version control or sent to us or anything: the source code of this whole thing is public so you're safe.
Caveat: Since your token is stored in node_modules
, your token will be removed on each npm install
of orval
.
You're done! 🎉
In some cases, you might need to augment an existing OpenAPI specification on the fly, for code-generation purposes. Our CLI makes this quite straightforward:
orval import --file myspec.yaml --output mybettercomponents.tsx --transformer path/to/my-transformer.js
The function specified in --transformer
is pure: it imports your --file
, transforms it, and passes the augmented OpenAPI specification to orval
's generator. Here's how it can be used:
// /path/to/my-transformer.js
/**
* Transformer function for orval.
*
* @param {OpenAPIObject} schema
* @return {OpenAPIObject}
*/
module.exports = inputSchema => ({
...inputSchema,
// Place your augmentations here
paths: Object.entries(schema.paths).reduce(
(mem, [path, pathItem]) => ({
...mem,
[path]: Object.entries(pathItem).reduce(
(pathItemMem, [verb, operation]) => ({
...pathItemMem,
[verb]: {
...fixOperationId(path, verb, operation),
},
}),
{},
),
}),
{},
),
});
orval
supports the concept of "schema stitching" in a RESTful ecosystem as well. We are able to tie multiple backends together and generate code using a single configuration file, orval.config.js
To activate this "advanced mode", replace all flags from your orval
call with the config flag: --config orval.config.js
(or any filename that you want).
⚠️ Note: using a config file makes use of all of the options contained therein, and ignores all other CLI flags.
interface RestfulClientConfig {
[backend: string]: {
// classic configuration
output: string;
file?: string;
types?: string;
github?: string;
transformer?: string;
validation?: boolean;
mock?: boolean;
};
}
// orval.config.js
module.exports = {
'petstore-file': {
file: 'examples/petstore.yaml',
output: 'examples/petstoreFromFileSpecWithConfig.tsx',
types: './model',
mock: true,
},
'petstore-file-transfomer': {
file: 'examples/petstore.yaml',
output: 'examples/petstoreFromFileSpecWithTransformer.tsx',
types: './model',
transformer: 'examples/transformer-add-version.js',
mock: {
properties: {
id: 'faker.random.number({ min: 1, max: 9999 })',
},
responses: {
listPets: {
properties: () => {
return {
id: 'faker.random.number({ min: 1, max: 9 })',
};
},
},
showPetById: {
data: () => ({
id: faker.random.number({ min: 1, max: 99 }),
name: faker.name.firstName(),
tag: faker.helpers.randomize([faker.random.word(), undefined]),
}),
},
},
},
},
};
// package.json
{
"scripts": {
"gen": "orval import --config orval.config.js",
"gen-first": "orval import --config orval.config.js myFirstBackend"
}
}
FAQs
A swagger client generator for typescript
The npm package orval receives a total of 203,279 weekly downloads. As such, orval popularity was classified as popular.
We found that orval demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.