Back

Step by Step Guide to Building a Microsoft SQL Server API Integration in JS

Aug 8, 20247 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of SQL Server API integration using JavaScript? Great! We'll be using the mssql package to make our lives easier. Let's get cracking!

Prerequisites

Before we jump in, make sure you've got:

  • Node.js and npm installed
  • A Microsoft SQL Server instance up and running
  • Some JavaScript and SQL knowledge under your belt

Got all that? Awesome! Let's move on.

Setting up the project

First things first, let's get our project set up:

mkdir sql-server-api cd sql-server-api npm init -y npm install mssql express

Easy peasy, right?

Configuring the database connection

Now, let's set up our database connection. Create a new file called db.js:

const sql = require('mssql'); const config = { user: 'your_username', password: 'your_password', server: 'your_server', database: 'your_database', options: { encrypt: true, // Use this if you're on Windows Azure trustServerCertificate: true // Use this if you're using a self-signed cert } }; const poolPromise = new sql.ConnectionPool(config) .connect() .then(pool => { console.log('Connected to MSSQL') return pool }) .catch(err => console.log('Database Connection Failed! Bad Config: ', err)) module.exports = { sql, poolPromise }

Creating API endpoints

Time to set up our Express server and define some routes. Create an index.js file:

const express = require('express'); const { sql, poolPromise } = require('./db'); const app = express(); app.use(express.json()); // We'll add our CRUD operations here app.listen(3000, () => console.log('Server running on port 3000'));

Implementing CRUD operations

Let's add our CRUD operations to index.js. We'll just do a simple example for each:

// READ app.get('/users', async (req, res) => { try { const pool = await poolPromise; const result = await pool.request().query('SELECT * FROM Users'); res.json(result.recordset); } catch (err) { res.status(500).json({ error: err.message }); } }); // CREATE app.post('/users', async (req, res) => { try { const { name, email } = req.body; const pool = await poolPromise; await pool.request() .input('name', sql.NVarChar, name) .input('email', sql.NVarChar, email) .query('INSERT INTO Users (Name, Email) VALUES (@name, @email)'); res.status(201).json({ message: 'User created successfully' }); } catch (err) { res.status(500).json({ error: err.message }); } }); // UPDATE app.put('/users/:id', async (req, res) => { try { const { id } = req.params; const { name, email } = req.body; const pool = await poolPromise; await pool.request() .input('id', sql.Int, id) .input('name', sql.NVarChar, name) .input('email', sql.NVarChar, email) .query('UPDATE Users SET Name = @name, Email = @email WHERE Id = @id'); res.json({ message: 'User updated successfully' }); } catch (err) { res.status(500).json({ error: err.message }); } }); // DELETE app.delete('/users/:id', async (req, res) => { try { const { id } = req.params; const pool = await poolPromise; await pool.request() .input('id', sql.Int, id) .query('DELETE FROM Users WHERE Id = @id'); res.json({ message: 'User deleted successfully' }); } catch (err) { res.status(500).json({ error: err.message }); } });

Error handling and best practices

Notice how we're using try-catch blocks? That's crucial for proper error handling. Also, we're using the connection pool for better performance and connection management.

Testing the API

Fire up your server with node index.js and use Postman or curl to test your endpoints. Go wild!

Security considerations

Remember, always validate your inputs and use parameterized queries (like we did) to prevent SQL injection attacks. Stay safe out there!

Conclusion

And there you have it! You've just built a Microsoft SQL Server API integration using JavaScript. Pretty cool, huh?

Remember, this is just the beginning. You can expand on this by adding more complex queries, implementing authentication, or even building a full-fledged application. The sky's the limit!

Keep coding, keep learning, and most importantly, have fun!