Building RESTful APIs
Building RESTful APIs is an essential part of modern web development. RESTful APIs allow frontend applications to interact with the backend server and perform data retrieval and manipulation operations on a database.
To build a RESTful API with database connectivity, you need to choose a backend framework, such as Express.js, and a database management system, such as MySQL.
Here's an example of how you can build a simple RESTful API with database connectivity using Express.js and MySQL:
JAVASCRIPT
1// Replace with JavaScript code that demonstrates building a RESTful API with database connectivity
2
3// Import required modules
4const express = require('express');
5const bodyParser = require('body-parser');
6const mysql = require('mysql');
7
8// Create connection to MySQL database
9const connection = mysql.createConnection({
10 host: 'localhost',
11 user: 'root',
12 password: 'password',
13 database: 'mydb'
14});
15
16// Create an instance of the Express application
17const app = express();
18
19// Configure body-parser to handle JSON data
20app.use(bodyParser.json());
21
22// Define routes
23app.get('/users', (req, res) => {
24 // Execute SQL query
25 const query = 'SELECT * FROM users';
26 connection.query(query, (error, results) => {
27 if (error) {
28 console.log('An error occurred:', error);
29 // Send error response
30 res.status(500).json({ error: 'Failed to fetch users' });
31 } else {
32 // Send success response
33 res.json(results);
34 }
35 });
36});
37
38// Start the server
39app.listen(3000, () => {
40 console.log('Server is running on port 3000');
41});
xxxxxxxxxx
41
});
// Replace with JavaScript code that demonstrates building a RESTful API with database connectivity
// Import required modules
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
// Create connection to MySQL database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
// Create an instance of the Express application
const app = express();
// Configure body-parser to handle JSON data
app.use(bodyParser.json());
// Define routes
app.get('/users', (req, res) => {
// Execute SQL query
const query = 'SELECT * FROM users';
connection.query(query, (error, results) => {
if (error) {
console.log('An error occurred:', error);
// Send error response
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment