Security News
Python Overtakes JavaScript as Top Programming Language on GitHub
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
swagger-client
Advanced tools
The swagger-client npm package is a JavaScript client for Swagger/OpenAPI specifications. It allows you to interact with APIs described by Swagger/OpenAPI documents, making it easier to consume and interact with RESTful services.
Initialize Client
This feature allows you to initialize a Swagger client by providing the URL to the Swagger/OpenAPI specification. The client can then be used to interact with the API described by the specification.
const Swagger = require('swagger-client');
const client = new Swagger({ url: 'http://petstore.swagger.io/v2/swagger.json' });
Make API Calls
This feature allows you to make API calls using the initialized client. In this example, the client is used to call the 'getPetById' operation from the Petstore API.
client.then(client => {
client.apis.pet.getPetById({ petId: 1 }).then(response => {
console.log(response);
});
});
Handle Authentication
This feature allows you to handle authentication by providing authorization details when initializing the client. In this example, an API key is provided for authentication.
const client = new Swagger({
url: 'http://petstore.swagger.io/v2/swagger.json',
authorizations: {
api_key: new Swagger.ApiKeyAuthorization('api_key', 'YOUR_API_KEY', 'query')
}
});
Axios is a promise-based HTTP client for the browser and Node.js. While it does not specifically target Swagger/OpenAPI specifications, it can be used to make HTTP requests to any API. Compared to swagger-client, axios is more general-purpose and does not provide built-in support for Swagger/OpenAPI documents.
openapi-client-axios is a package that combines the capabilities of Axios with OpenAPI specifications. It allows you to generate an Axios client from an OpenAPI document, similar to swagger-client. However, it leverages Axios for making HTTP requests, providing a more flexible and widely-used HTTP client.
swagger-js is another JavaScript client for Swagger/OpenAPI specifications. It provides similar functionality to swagger-client, allowing you to interact with APIs described by Swagger/OpenAPI documents. The main difference is in the implementation and API design, but both packages serve the same purpose.
Swagger Client is a JavaScript module that allows you to fetch, resolve, and interact with Swagger/OpenAPI documents.
This is the new version of swagger-js, 3.x. The new version supports Swagger 2.0 as well as OpenAPI 3.
Want to learn more? Check out our FAQ.
For the older version of swagger-js, refer to the 2.x branch.
The npm package is called swagger-client
and the GitHub repository is swagger-js
.
We'll be consolidating that soon. Just giving you the heads up. You may see references to both names.
npm install swagger-client
import Swagger from 'swagger-client'
// Or commonjs
const Swagger = require('swagger-client')
<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
<script>
var swaggerClient = new SwaggerClient(specUrl);
</script>
This lib exposes these functionalities for Swagger 2.0 and OpenAPI 3:
url
or spec
from the instancehttp
and spec
instance propertiesSwagger.http(req)
exposes a Fetch-like interface with a twist: allowing url
in the request object so that it can be passed around and mutated. It extends Fetch to support request and response interceptors and performs response & header serialization. This method could be overridden to change how SwaggerJS performs HTTP requests.
// Fetch-like, but support `url`, `query` and `xxxInterceptor`
const request = {
url,
query,
method,
body,
headers,
requestInterceptor,
responseInterceptor,
userFetch
}
Swagger.http(request)
.then((res) => {
res.statusCode // status code
res.statusText // status text, ie: "Not Found"
res.body // JSON object or undefined
res.obj // same as above, legacy
res.text // textual body, or Blob
res.headers // header hash
})
.catch((err) => {
err // instanceof Error
err.response // response or null
})
// Interceptors
Swagger.http({
requestInterceptor: (req: Request) => Request | Promise<Request>
responseInterceptor: (res: Response) => Response | Promise<Response>
})
// Custom Fetch
Swagger.http({
userFetch: (url: String, options: Object) => Promise
})
Swagger.resolve({url, spec, http})
resolves $ref
s (JSON-Refs) with the objects they point to.
Swagger.resolve({url, spec, http}).then((resolved) => {
resolved.errors // resolution errors, if any
resolved.spec // the resolved spec
})
This is done automatically if you use the constructor/methods
An HTTP client for OAS operations, maps an operation and values into an HTTP request.
const params = {
spec,
operationId, // Either operationId, or you can use pathName + method
(pathName),
(method),
parameters, // _named_ parameters in an object, eg: { petId: 'abc' }
securities, // _named_ securities, will only be added to the request, if the spec indicates it. eg: {apiKey: 'abc'}
requestContentType,
responseContentType,
(http), // You can also override the HTTP client completely
(userFetch), // Alternatively you can just override the fetch method (if you want to use request.js or some other HttpAgent)
}
// Creates a request object compatible with HTTP client interface.
// If `pathName` and `method`, then those are used instead of operationId. This is useful if you're using this dynamically, as `pathName` + `method` are guarenteed to be unique.
const res = Swagger.execute({...params})
// You can also generate just the request ( without executing... )
const req = Swagger.buildRequest({...params})
Resolve the spec and expose some methods that use the resolved spec:
Swagger(url, opts): Promise
execute
, http
, resolve
and some other minor ones#http
, #execute
and #resolve
bound to the instanceSwagger('http://petstore.swagger.io/v2/swagger.json')
.then( client => {
client.spec // The resolved spec
client.originalSpec // In case you need it
client.errors // Any resolver errors
// Tags interface
client.apis.pet.addPet({id: 1, name: "bobby"}).then(...)
// TryItOut Executor, with the `spec` already provided
client.execute({operationId: 'addPet', parameters: {id: 1, name: "bobby"}}).then(...)
})
A client for operations. We're currently using the apis[tag][operationId]:ExecuteFunction
interface, which can be disabled entirely using Swagger({disableInterfaces: true})
if you don't need it.
OperationId's are meant to be unique within spec, if they're not we do the following:
default
as the internal tag${method}${path}
, with non-alphanumeric characters escaped to _
. See these tests (1, 2) for examples.Swagger({ url: "http://petstore.swagger.io/v2/swagger.json" }).then((client) => {
client
.apis
.pet // tag name == `pet`
.addPet({ // operationId == `addPet`
id: 1,
body: {
name: "bobby",
status: "available"
}
})
.then(...)
})
If you'd like to use the operationId formatting logic from Swagger-Client 2.x, set the v2OperationIdCompatibilityMode
option:
Swagger({
url: "http://petstore.swagger.io/v2/swagger.json",
v2OperationIdCompatibilityMode: true
}).then((client) => {
// do things as usual
})
OpenAPI 3.0 definitions work in a similar way with the tags interface, but you may need to provide additional data in an options
object for server variables and request bodies, since these items are not actual parameters:
Swagger({...}).then((client) => {
client
.apis
.pet // tag name == `pet`
.addPet({ // operationId == `addPet`
id: 1
}, {
requestBody: {
name: "bobby",
status: "available"
},
server: "http://petstore.swagger.io/{apiPrefix}/", // this should exactly match a URL in your `servers`
serverVariables: {
apiPrefix: "v2"
}
})
.then(...)
})
If you need activate CORS requests, just enable it by withCredentials
property at http
<html>
<head>
<script src='//unpkg.com/swagger-client' type='text/javascript'></script>
<script>
var specUrl = 'http://petstore.swagger.io/v2/swagger.json'; // data urls are OK too 'data:application/json;base64,abc...'
SwaggerClient.http.withCredentials = true; // this activates CORS, if necessary
var swaggerClient = new SwaggerClient(specUrl)
.then(function (swaggerClient) {
return swaggerClient.apis.pet.addPet({id: 1, name: "bobby"}); // chaining promises
}, function (reason) {
console.error("failed to load the spec" + reason);
})
.then(function(addPetResult) {
console.log(addPetResult.obj);
// you may return more promises, if necessary
}, function (reason) {
console.error("failed on API call " + reason);
});
</script>
</head>
<body>
check console in browser's dev. tools
</body>
</html>
SwaggerJS has some legacy signature shapes.
// swagger-js
{
url,
method,
status,
statusText,
headers,
data, // The textual content
obj // The body object
}
// New shape
{
url,
method,
status,
statusText,
headers, // See note below regarding headers
text, // The textual content
body, // The body object
}
By default the instance version of #http
serializes the body and headers.
However, headers pose an issue when there are multiple headers with the same name.
As such we've left the static version of http
to not perform any serialization.
npm install
npm run test # run test
npm run test:unit:watch # run test with change watching
npm run test:lint # run lint
npm run build # package to release
npm run build:umd:watch # package with non-minified dist/index.js (for debugging)
npm run build:bundle # build browser version available at .../browser/index.js
There has been a complete overhaul of the codebase. For notes about how to migrate coming from 2.x, please see Migration from 2.x
Please disclose any security-related issues or vulnerabilities by emailing security@swagger.io, instead of using the public issue tracker.
For features known to be missing from 3.x please see the Graveyard
FAQs
SwaggerJS - a collection of interfaces for OAI specs
The npm package swagger-client receives a total of 445,253 weekly downloads. As such, swagger-client popularity was classified as popular.
We found that swagger-client demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 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
Python becomes GitHub's top language in 2024, driven by AI and data science projects, while AI-powered security tools are gaining adoption.
Security News
Dutch National Police and FBI dismantle Redline and Meta infostealer malware-as-a-service operations in Operation Magnus, seizing servers and source code.
Research
Security News
Socket is tracking a new trend where malicious actors are now exploiting the popularity of LLM research to spread malware through seemingly useful open source packages.