Swagger Codegen - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
The Swagger Codegen is an open source code-generator to build server stubs and client SDKs directly from a Swagger defined RESTful API.
- Client SDKs: libraries for calling the API easily for different platforms: javascript (browser), node, java (for Android or java application), Objective-C (Mac or iOS),...
- Server Stubs: (need to check again) server side code for the API (this is just stub: ie: there is no logic in it but returning default values) - php ...
- Documentation of the API.
Excellent point: We are focus on the main task; ie: creating the API. Boiler plate code are generated. Test cases are also generated in a template. This is a very good starting point for writing tests.
Java, version 7 or higher
-
Download appropriate version (should be latest) from Maven
https://oss.sonatype.org/content/repositories/releases/io/swagger/swagger-codegen-cli/ -
Run command for generating code:
java -jar swagger-codegen-cli-2.2.1.jar generate -i petstore.json -o javascript -l javascript
* `-i petstore.json`: swagger document specification input file
* `-o javascript`: output code will be placed in `javascript` folder
* `-l javascript`: parsing language
PetStore API is an Restful API which provides api for managing pets, store inventory and users.
-
Get swagger file of PetStore API
Download sample document specification Petstore file -
Generate javascript code for Petstore API: - Copy to the same folder with
swagger-codegen-cli-x.x.x.jar
- Opencmd
, go to the folder, run command
java -jar swagger-codegen-cli-2.2.1.jar generate -i petstore.json -o javascript -l javascript
- Use the generated code on the page:
- Go to generated code folder, ex:D:\Swagger\javascript\
- Download superagent library, place it on current folder.
- Createindex.html
file
* Includerequire.js
from https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.js
* requireindex.js
* CallfindPetsByStatus
method fromPetApi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello Swagger</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.js"></script>
<script>
require(['index'], function(SwaggerPetstore) {
var apiInstance = new SwaggerPetstore.PetApi();
apiInstance.findPetsByStatus(["available"], function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ');
console.log(JSON.stringify(data));
// data.forEach(function(pet){
// console.log(pet.name + ', ' + pet.category.name);
// });
}
});
});
</script>
</body>
</html>