{"id":14986645,"url":"https://github.com/olaferlandsen/angular-swagger2-client","last_synced_at":"2025-04-11T23:01:42.786Z","repository":{"id":57179191,"uuid":"79561017","full_name":"olaferlandsen/angular-swagger2-client","owner":"olaferlandsen","description":"A simple and powerful swagger client for angular 1.4+","archived":false,"fork":false,"pushed_at":"2017-10-11T21:28:26.000Z","size":82,"stargazers_count":2,"open_issues_count":2,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-25T18:54:02.495Z","etag":null,"topics":["angular","angularjs","openapi","swagger-specification","swaggerclient"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/olaferlandsen.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-20T13:24:28.000Z","updated_at":"2017-10-10T02:51:14.000Z","dependencies_parsed_at":"2022-09-09T17:30:50.267Z","dependency_job_id":null,"html_url":"https://github.com/olaferlandsen/angular-swagger2-client","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olaferlandsen%2Fangular-swagger2-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olaferlandsen%2Fangular-swagger2-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olaferlandsen%2Fangular-swagger2-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/olaferlandsen%2Fangular-swagger2-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/olaferlandsen","download_url":"https://codeload.github.com/olaferlandsen/angular-swagger2-client/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247983091,"owners_count":21028243,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","angularjs","openapi","swagger-specification","swaggerclient"],"created_at":"2024-09-24T14:13:16.654Z","updated_at":"2025-04-11T23:01:42.766Z","avatar_url":"https://github.com/olaferlandsen.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Angular OpenAPI/Swagger Client\nA simple and powerful OpenAPI/Swagger Client for Angular, based on promises to connect with endpoint using [OpenAPI/Swagger Specification 2.0](http://swagger.io/).\n\n## Features\n* `POST`, `PUT`, `GET`, `DELETE`, `PATCH` and `CONNECT` request are supported.\n* Params in: `query`, `path`, `formData` and `header` are supported.\n* `SecuritySchema` with `security` in API are supported(only type `apiKey`).\n* By default, `PUT` and `POST` request send with `content-type: application/x-www-form-urlencoded`.\n* Removes all parameters that have not been established in the API definition.\n* Implements a Pre-Validator for params and supported `data types`, `format` and `required`.\n* Global static and dynamic default value based on LocalStorage.\n* Support for uploading files using [consume](http://swagger.io/specification/#operation-object-36) in the API definition and with at least one parameter in [formData](http://swagger.io/specification/#parameterObject).\n\n## Getting Started\n\n### Install\n#### Install via NPM\n```bash\nnpm install angular-swagger2-client\n```\n#### Install via Bower\n```bash\nbower install angular-swagger2-client\n```\n\n## Start Using\n### Include\nInclude the required libraries in your `index.html`:\n```html\n\u003chtml\u003e\n    \u003chead\u003e\n        \u003ctitle\u003eMy Angular Application\u003c/title\u003e\n        \u003c!-- Angular swagger Client --\u003e\n        \u003cscript src=\"vendor/angular-swagger2-client/dist/angular-swagger2-client.js\"\u003e\u003c/script\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        ...\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\u003e **IMPORTANT:** Where `vendor` you need replace for you downaload directory. If you ussing `bower` replace for `bower_components`, and if you using `npm` you need replace for `node_modules`\n* Inject `angular-swagger2-client` module\n\n### Inject\n**angular-swagger2-client** have to be injected to your angular application as a dependency\n```javascript\nangular.module('myApp', [\n  'angular-swagger2-client'\n])\n```\n\n### Prepare you OpenAPI/Swagger\n#### Synchronous swagger.json load\nIf you have content of your api's *swagger.json* available at config time you can use **angular-swagger2-client** like this:\n```javascript\nangular.module('myApp', [\n  'angular-swagger2-client'\n])\n  .value('SwaggerData', SwaggerData) // Your api's swagger.json as a javascript object\n  .provider('Api', Api); // Define Api provider\n\nfunction Api() {\n  // This is fully described in Provider Recipe in angularjs [docs](https://docs.angularjs.org/guide/providers#provider-recipe)\n  // $get is called during dependency injection. By this your service can use other services (like SwaggerData) as dependency\n  this.$get = function(AngularSwagger2Client, SwaggerData) {\n    return new AngularSwagger2Client(SwaggerData)\n  };\n}\n```\n\n#### Asynchronous swagger.json load\nSometimes our *swagger.json* is hosted on the api server and we need to load it using AJAX.\nSo we need to use **lazy loading** pattern\n```javascript\nangular.module('myApp', [\n  'angular-swagger2-client'\n])\n  .constant('API_URL', 'https://api.my-service.com') // Url of our api server which swagger.json is hosted there\n  .provider('Api', Api); // Define Api provider\n\nfunction Api() {\n  var deferred;\n\n  // This is fully described in Provider Recipe in angularjs [docs](https://docs.angularjs.org/guide/providers#provider-recipe)\n  // $get is called during dependency injection. By this your service can use other services (like $http) as dependency\n  this.$get = function($http, $q, API_URL, AngularSwagger2Client) {\n    if (undefined === deferred) {\n      deferred = $q.defer();\n    }\n\n    $http.get(API_URL + \"/swagger.json\")\n      .success(function (data) {\n        // Uncomment this if you don't have 'host' key defined in your swagger.json\n        // 'host' have to refer to your API_URL without http/https://\n        // data.host = API_URL.replace(/^https?\\:\\/\\//, \"\");\n\n        deferred.resolve(new AngularSwagger2Client(data));\n      })\n      .error(function (data) {\n        deferred.reject(data);\n      });\n\n    return {\n      load: function () {\n        return deferred.promise;\n      }\n    };\n  };\n}\n```\n\n### Communicating with your API\nYour API methods are accessible using:\n```javascript\nAngularSwagger2Client.api[namespace][operationId](parameters, configuration)\n  .then(function (response) {\n      // Data is available in response.data\n      // Status is available in response.status\n      // Status Text is available in response.statusText\n  })\n  .catch(function (response) {\n      // Data is available in response.data\n      // Status is available in response.status\n      // Status Text is available in response.statusText\n\n      // If rejection was due to Validation errors they're available in response.validation array\n  });\n```\n**namespace** is a slug (all braces \\[,\\],\\{ and \\} are removed) of one of these in priority:\n* path's first tag\n* first part of the path (/entities/{entityId} --\u003e entities)\n* first part of the baePath (/api --\u003e api)\n\n#### *`object`* parameters **`optional`**\nUse **parameters** to pass any *query*, *path*, *header* and *body* parameters\n\n#### *`object`* configuration **`optional`**\nUse **configuration** for any $http() method input\n\u003e **IMPORTANT:** Setting configuration may overwrite request config which are created by **angular-swagger2-client** (which are **url**, **method**, **data**, **headers** keys) to create api call in fact causes malfunction\n\n#### Example API Definition\nSuppose this *swagger.yml* describes your api and your *swagger.json* is generated based on it:\n```yaml\nswagger: '2.0'\ninfo:\n  title: my awesome api\n  version: 2.0.0\nschemes:\n  - http\nconsumes:\n  - application/my.awesome.api.v1+json\n  - application/json\n  - text/plain\nproduces:\n  - application/my.awesome.api.v1+json\n  - application/json\n\nsecurityDefinitions:\n  key:\n    type: apiKey\n    in: query\n    name: token\n  basic:\n    type: basic\nsecurity:\n  - key: []\n\nparameters:\n  pageParam:\n    name: page\n    in: query\n    description: Desired page number in a paginated result set\n    type: integer\n    format: int32\n    minimum: 1\n    default: 1\n  pageSizeParam:\n    name: pageSize\n    in: query\n    description: Desired page size in a paginated result set\n    type: integer\n    format: int32\n    minimum: 1\n    default: 10\n\npaths:\n  /sessions:\n    post:\n      security:\n        - basic: []\n      tags:\n        - sessions\n      summary: Set up a new session by providing correct credentials\n      operationId: createSession\n      responses:\n        201:\n          description: Created\n          schema:\n            $ref: \"#/definitions/session\"\n        default:\n          description: Error\n          schema:\n            $ref: \"#/definitions/error\"\n    delete:\n      tags:\n        - sessions\n      summary: Revoke an existing session\n      operationId: deleteSession\n      responses:\n        200:\n          description: Revoked\n        default:\n          description: Error\n          schema:\n            $ref: \"#/definitions/error\"\n\n  /entities:\n    get:\n      tags:\n        - entities\n      operationId: getEntities\n      summary: Get list of filtered and paginated entities\n      parameters:\n        - name: keyword\n          type: string\n          in: query\n        - $ref: '#/parameters/pageParam'\n        - $ref: '#/parameters/pageSizeParam'\n      responses:\n        200:\n          description: Ok\n          schema:\n            allOf:\n              - $ref: \"#/definitions/paginated\"\n              - type: object\n                properties:\n                  entities:\n                    type: array\n                    items:\n                      $ref: \"#/definitions/entity\"\n        404:\n          description: Nothing found\n          schema:\n            $ref: \"#/definitions/paginated\"\n        default:\n          description: error\n          schema:\n            $ref: \"#/definitions/error\"\n\n  /entities/{entityId}:\n      parameters:\n        - name: entityId\n          required: true\n          in: path\n          type: integer\n          format: int32\n      delete:\n        tags:\n          - entities\n        operationId: deleteEntity\n        summary: Delete one entity\n        responses:\n          204:\n            description: Deleted one\n          default:\n            description: error\n            schema:\n              $ref: \"#/definitions/error\"\n\ndefinitions:\n  credentials:\n    type: object\n    required:\n      - username\n      - secret\n    properties:\n      username:\n        type: string\n        description: Username of the user\n      secret:\n        type: string\n        description: Secret key of the user\n\n  session:\n    type: object\n    required:\n      - username\n      - token\n    properties:\n      username:\n        type: string\n        description: Username of the session owner\n      token:\n        type: string\n        description: Access token of the current session. Which will be used as security key in further requests\n\n  entity:\n    type: object\n    required:\n      - entityId\n      - name\n    properties:\n      entityId:\n        type: integer\n        format: int32\n        readOnly: true\n        description: Internal identifier of an entity\n      name:\n        type: string\n        description: Name of an entity\n\n  error:\n    type: object\n    required:\n       - message\n    properties:\n      code:\n        type: integer\n        format: int64\n      message:\n        type: string\n      fields:\n        type: array\n        items:\n          type: string\n\n  paginated:\n    type: object\n    required:\n      - count\n      - pageCount\n    properties:\n      count:\n        type: integer\n        format: int32\n      pageCount:\n        type: integer\n        format: int32\n```\n\n#### Sign In using Basic Auth (sessions.createSession)\nProvide **User**\n```javascript\nangular.module('myApp', [\n  'angular-md5', // angular-md5 to create password hash in sign in process\n  'angular-swagger2-client'\n])\n  .provider('User', User);\n\nfunction User() {\n  this.$get = function(localStorage) {\n    return {\n      /** @return string */\n      GetUsername: function () {\n        var user = localStorage.getObject('user');\n        if (undefined !== user) {\n          if (user.hasOwnProperty('username')) {\n            return user.username;\n          }\n        }\n\n        return \"\";\n      },\n\n      /** @return string */\n      GetToken: function () {\n        var user = localStorage.getObject('user');\n        if (undefined !== user) {\n          if (user.hasOwnProperty('token')) {\n            return user.token;\n          }\n        }\n\n        return \"\";\n      }\n    };\n  };\n}\n```\n\n**localStorage** Service for current user username and token storage\n```javascript\nangular.module('myApp.services.localStorage', [])\n  .service('localStorage', localStorage);\n\n/** @ngInject */\nfunction localStorage($window) {\n  return {\n    set: set,\n    get: get,\n    setObject: setObject,\n    getObject: getObject,\n    clear: clear\n  };\n\n  function set(key, value) {\n    if ($window.fakeLocalStorage) {\n      $window.fakeLocalStorage[key] = value;\n    } else {\n      $window.localStorage[key] = value;\n    }\n  }\n\n  function get(key, defaultValue) {\n    return !$window.fakeLocalStorage ?\n      $window.localStorage[key] || defaultValue :\n      $window.fakeLocalStorage[key] || defaultValue;\n  }\n\n  function setObject(key, value) {\n    if ($window.fakeLocalStorage) {\n      $window.fakeLocalStorage[key] = angular.toJson(value);\n    } else {\n      $window.localStorage[key] = angular.toJson(value);\n    }\n  }\n\n  function getObject(key) {\n    return !$window.fakeLocalStorage ?\n      angular.fromJson($window.localStorage[key] || '{}') :\n      angular.fromJson($window.fakeLocalStorage[key] || '{}');\n  }\n\n  function clear() {\n    if ($window.fakeLocalStorage) {\n      $window.fakeLocalStorage = {};\n    } else {\n      $window.localStorage.clear();\n    }\n  }\n}\n```\n\nSign In Page Controller\n```javascript\nangular.module('myApp.pages.signIn')\n  .controller('SignInPageCtrl', SignInPageCtrl);\n\n/** @ngInject */\nfunction SignInPageCtrl(localStorage, $state, Api, md5, toastr, $q) {\n  var vm = this;\n\n  // Form\n  vm.form = {\n    model: {\n      username: '',\n      password: ''\n    }\n  };\n\n  vm.form.validate = function (model) {\n    var deferred = $q.defer();\n    var errors = [];\n\n    if (0 === model.username.trim().length) {\n      errors.push({\n        'field': 'username',\n        'message': \"Username can't be empty or whitespace\"\n      });\n    }\n\n    if (0 === model.password.trim().length) {\n      errors.push({\n        'field': 'password',\n        'message': \"Password can't be empty or whitespace\"\n      });\n    }\n\n    if (errors.length \u003e 0) {\n      deferred.reject(errors);\n    } else {\n      deferred.resolve(model);\n    }\n\n    return deferred.promise;\n  };\n\n  vm.form.sanitize = function (model) {\n    var deferred = $q.defer();\n    var cleanModel = model;\n\n    cleanModel.username = model.username.trim();\n    cleanModel.password = model.password.trim();\n\n    deferred.resolve(cleanModel);\n\n    return deferred.promise;\n  };\n\n  vm.signIn = function () {\n    vm.form.validate(vm.form.model)\n      .catch(function (errors) {\n        // Validation error\n\n        for (var i in errors) {\n          toastr.error(errors[i].message, 'Form invalid');\n        }\n\n        return Promise.reject(errors);\n      })\n      .then(vm.form.sanitize)\n      .then(function (model) {\n        return Api.load().then(function (client) {\n          client.api.sessions.createSession({\n            Authorization: 'Basic ' + btoa(model.username + ':' + md5.createHash(model.password))\n          })\n            .then(function (response) {\n              // Login successful\n              localStorage.setObject('user', {username: response.data.username, token: response.data.token});\n\n              $state.go('dashboard');\n            })\n            .catch(function (response) {\n              // Login failed\n              var msg = 'Invalid Credentials';\n\n              switch (response.status) {\n                case 500:\n                  msg = 'Server inaccessible';\n                  break;\n              }\n\n              toastr.error(msg, 'SignIn Failed');\n            });\n        });\n      });\n  };\n}\n```\n\n#### Sign Out (sessions.deleteSession)\n```javascript\nangular.module('myApp.pages.signOut')\n  .controller('SignOutPageCtrl', SignOutPageCtrl);\n\n/** @ngInject */\nfunction SignOutPageCtrl(localStorage, $state, Api, User) {\n  Api.load().then(function (client) {\n    client.api.sessions.deleteSession({\n      token: User.GetToken()\n    });\n  });\n\n  localStorage.clear();\n\n  $state.go('dashboard');\n}\n```\n\n#### Working with entities\n```javascript\nangular.module('myApp.pages.entities')\n  .controller('EntitiesPageCtrl', EntitiesPageCtrl);\n\n/** @ngInject */\nfunction EntitiesPageCtrl(Api, User, $q) {\n    var vm = this;\n    \n    vm.entities = {\n      count: 0,\n      pageCount: 0,\n      list: []\n    };\n    \n    // Get filtered and paginated list of entities\n    vm.loadEntities = function (search, page, pageSize) {\n      return Api.load().then(function (client) {\n        var query = {\n          token: User.GetToken()\n        };\n\n        // Search\n        if (undefined !== search) {\n          if (undefined !== search.keyword) {\n            query.keyword = search.keyword;\n          }\n        }\n\n        // Pagination - Page Number\n        if (undefined !== page) {\n          query.page = page;\n        }\n\n        // Pagination - Page Size\n        if (undefined !== pageSize) {\n          query.pageSize = pageSize;\n        }\n\n        var deferred = $q.defer();\n        \n        client.api.entities.getEntities(query)\n          .then(function (response) {\n            vm.entities.count = response.data.count;\n            vm.entities.pageCount = response.data.pageCount;\n            vm.entities.list = [];\n\n            for (var i in response.data.entities) {\n              var entity = response.data.entities[i];\n              vm.entities.list.push({\n                id: entity.entityId,\n                name: entity.name\n              });\n            }\n            \n            deferred.resolve(vm.entities);\n          })\n          .catch(function (response) {\n            deferred.reject(response);\n          });\n        \n        return deferred.promise;\n      });\n    };\n    \n    // Delete an entity\n    vm.deleteEntity = function (id) {\n      Api.load().then(function (client) {\n        var query = {\n          token: User.GetToken(),\n          entityId: id\n        };\n\n        client.api.entities.deleteEntity(query)\n          .then(function (response) {\n            // Your entity has been deleted\n          })\n          .catch(function (response) {\n            // Prompt user: delete failed\n          });\n      });\n    };\n    \n    vm.loadEntities()\n      .then(function () {\n          // Your vm.entities is ready\n      });\n}\n```\n\n## Requirements\n* AngularJS 1.4+\n\n## API\n\n```javascript\nobject AngularSwagger2Client(Object jsonObject[, Object defaultStaticData[, Array defaultDynamicData]])\n```\n\n### Params\n\n#### *`object`* jsonObject **`required`**\nThis param is required and expect a json object of swagger.\n\u003e **IMPORTANT:** Only accepts the OpenAPI/Swagger Specification version 2.0.\n\n#### *`object`* defaultStaticData **`optional`**\nThis parameter only accepts an object with keys and their respective values that will be used by default in all API's.\n\u003e **IMPORTANT:** Parameters that have not been defined in the `parameterObject` or `securityRequirementObject` will not be used.\n\n#### *`array`* defaultDynamicData **`optional`**\nThis parameter only accepts an array with the list of localStorage keys. These keys are processed at runtime to ensure current values are obtained.\n\u003e **IMPORTANT:** Parameters that have not been defined in the `parameterObject` or `securityRequirementObject` will not be used.\n\n\n## Thanks:\n* [@pouyanh](https://github.com/pouyanh) - [Basic-Authentication](https://github.com/olaferlandsen/angular-swagger2-client/pull/2), [security](https://github.com/olaferlandsen/angular-swagger2-client/pull/3) and [improves](https://github.com/olaferlandsen/angular-swagger2-client/pull/4).\n* [@TomStanczyk](https://github.com/TomStanczyk) - fix bower error.\n\nThis project is based on the [angular-swaggerific](https://github.com/TradeRev/angular-swaggerific) repository.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folaferlandsen%2Fangular-swagger2-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Folaferlandsen%2Fangular-swagger2-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Folaferlandsen%2Fangular-swagger2-client/lists"}