Creating a Route with Simple Validation in AdonisJS: A Beginner's Guide
Hey there! In this post, we're going to learn how to create a route with simple validation in AdonisJS. This is a beginner-friendly tutorial, so don't worry if you're new to AdonisJS or web development in general.
Installation
First things first, let's make sure we have AdonisJS installed. Open up your terminal and run the following command:
npm install -g @adonisjs/cli
This will install the AdonisJS CLI globally on your machine, so you can use it to create new AdonisJS projects and run commands.
Next, let's create a new AdonisJS project. Open up your terminal and run the following command:
adonis new simple-api && cd simple-api
This will create a new AdonisJS project in a directory called simple-api.
Create route
Now, let's create a route with simple validation. Open up the start/routes.js file in your text editor and add the following code:
const Route = use('Route')
const { validate } = use('Validator')
Route.post('/users', async ({ request, response }) => {
const validationRules = {
username: 'required|unique:users,username',
email: 'required|email|unique:users,email',
password: 'required|min:8'
}
const validation = await validate(request.all(), validationRules)
if (validation.fails()) {
return response.badRequest(validation.messages())
}
const user = await User.create(request.all())
return response.created(user)
})
Let's break down what this code does. First, we import the Route and Validator modules. Then, we define a POST route at /users. This route expects three parameters: username, email, and password.
We define validation rules for these parameters using the validate function from the Validator module. The rules are:
username
: Required, and must be unique in the users table.
email
: Required, must be a valid email address, and must be unique in the users table.
password
: Required, and must have a minimum length of 8 characters.
We then use the validate function to validate the incoming request against these rules. If validation fails, we return a 400 Bad Request response with the validation error messages. If validation passes, we create a new user and return a 201 Created response with the newly created user.
Run app
Once you have created your application, the next step is to start the development server. You can do this by running the following command:
node ace serve --watch
If you want to test your application, I suggest using Postman. It's a tool for testing APIs that lets you create requests and see responses in an easy-to-use interface.
And that's it! You've created a route with simple validation in AdonisJS. Now you can test your route by sending a POST request to /users with the required parameters. If the parameters pass validation, a new user will be created and returned in the response.
I hope you found this tutorial helpful. If you have any questions or feedback, feel free to leave a comment below. Happy coding! 🤗