Let's see how easily and quickly you can get a simple API up and running using swagger.
First, we create a new swagger project and test a simple "hello world" API.
-
Install swagger, as described in the installation guide.
-
Create swagger project directory and cd to it. This is where you'll create your first project.
-
Execute the project create command:
swagger project create hello-world
-
Pick the API framework you want to use. We're going to pick express, but you can pick any of the listed frameworks:
? Framework? (Use arrow keys) connect ❯ express hapi restify sails
Note: You must enter the number of the option.
-
swagger creates a skeleton project that's pre-configured to use your selected framework (in this example, Express). It then runs
npm install
to pick up the dependencies.Note: Windows users see the note below regarding npm.
-
Change to the new project directory:
cd hello-world
-
Type
swagger project start
to start your API. You now have an API running with swagger! -
In another terminal, run this command:
curl http://127.0.0.1:10010/hello?name=Scott
And, you'll get back the response
Hello, Scott
.
That's it - You have now created, started and tested your first API project with swagger!
Open /app.js in an editor. This is the main Node.js app that installs middleware and requires the API framework that you chose when you created your project.
The middleware modules perform tasks like OpenAPI Specification validation and endpoint routing. For more information, see swagger modules and dependencies.
The Swagger editor lets you design and test your API interactively. While you design and test, the API documentation is generated automatically for you.
Now that we've got our basic API running, let's open the Swagger editor.
-
Be sure you're in your project root directory:
./hello-world
. -
Fire up the editor:
swagger project edit
When you run a swagger-node based application in a proper deployment, you should use node <entrypoint>
(typically, node app.js
) as opposed to using the swagger cli tooling.
For some versions of npm on Windows will have problems on the npm install
step of swagger project create
. They are related to a debug
module on npm not being managed properly. The following steps should resolve this issue:
- In the project directory, execute the following commands:
npm install yamljs
npm install debug
npm install swagger-tools
Now, when you run swagger project start
your project should start successfully.