How to start with APIs in SailsJS

Hello guys, in my previous post Beginners guide to Sails.js I’ve mentioned Sails’ auto generated APIs. Sails has an awesome feature of creating new API’s easily with default functionalities.

Here’s the way to create one:

sails generate api users

1-create

This will create new controller and model files in your project directory. In Controller folder, this will create UsersController.js and in model folder, this will create UsersModel.js file. Routes would be in controller file.

Now, to test the API, lift your server and run API in POSTMAN.

First start your project using this command:

sails lift

Create User

Now, open POSTMAN and send following JSON data on http://localhost:1337/users URL

{
"username":"codeportal123",
"password":"code123portal"
}

(You can also send you own JSON. Test your JSON is valid or not here)

2-create_user

Once you hit SEND button you’ll see one user has been created as displays in screenshot.

 

Get Users

Now that we’ve created user, let’s fetch all users

3-get_users

 

Update User

4-update_user

Now there’s slight difference in API url. We’ve added id of user that we want to update in query parameters so our API can know which user to update.

 

Delete User

Finally, delete user. URL format will be same as Update User. In this we are going to call DELETE method instead of GET or POST

5-delete_user

 

This are the basic operations we have reviewed but Sails provides more than this. We can do limit, filter the data, get data by different column names and etc…

Find our more about this here