Use Node.js for REST API on Localhost and use in Delphi
To create a REST API on your hosting, you can use a web framework such as Express.js or Flask. These frameworks make it easy to build web applications that can handle HTTP requests and responses. Here’s a brief overview of how to create a REST API using Express.js:
- Install Node.js and npm on your hosting. You can follow the installation instructions on the Node.js website.
- Create a new project directory and initialize a new npm project:
mkdir myapi
cd myapi
npm init
Install the Express.js framework and a database driver, such as mongoose:
npm install express mongoose
Create a new file called server.js
and add the following code to it:
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
// create a new Express app
const app = express();
// use the bodyParser middleware to parse JSON request bodies
app.use(bodyParser.json());
// connect to the database
mongoose.connect(‘mongodb://localhost/mydatabase’, {
useNewUrlParser: true,
useUnifiedTopology: true
});
// define a database schema
const userSchema = new mongoose.Schema({
username: String,
email: String,
password: String
});
// create a database model
const User = mongoose.model(‘User’, userSchema);
// define a route to get all users
app.get(‘/users’, async (req, res) => {
const users = await User.find();
res.json(users);
});
// define a route to create a new user
app.post(‘/users’, async (req, res) => {
const user = new User(req.body);
await user.save();
res.json(user);
});
// define a route to update a user
app.put(‘/users/:id’, async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body);
res.json(user);
});
// define a route to delete a user
app.delete(‘/users/:id’, async (req, res) => {
const user = await User.findByIdAndDelete(req.params.id);
res.json(user);
});
// start the server
app.listen(3000, () => {
console.log(‘Server started on port 3000’);
});
Run the server using the following command:
node server.js
ow you have a working REST API that can handle HTTP requests to retrieve, create, update, and delete user data from your database.
Connecting to the API from Delphi:
To connect to the REST API from a Delphi application, you can use the TRESTClient and TRESTRequest components that are included in Delphi’s REST client library. Here’s a brief overview of how to use these components to retrieve user data from the API:
- Open a new Delphi project and add a TRESTClient component to the form.
- Set the BaseURL property of the TRESTClient component to the URL of your API, e.g.
localhost:3000
. - Add a TRESTRequest component to the form.
- Set the Client property of the TRESTRequest component to the TRESTClient component you added in step 1.
- Set the Resource property of the TRESTRequest component to the endpoint you want to retrieve data from, e.g.
/users
. - Set the Method property of the TRESTRequest component to
rmGET
. - Add a TRESTResponse component to the form.
- Set the Request property of the TRESTResponse component to the TRESTRequest component you added in step 3.
- Call the Execute method of the TRESTRequest component to send the request to the API and retrieve the data.
- Use the Content property of the TRESTResponse component to access the JSON response from the API.
- Here’s an example of how to retrieve user data from the API using the TRESTClient and TRESTRequest components:
procedure TForm1.Button1Click(Sender: TObject);
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
Users: TJSONArray;
User: TJSONObject;
I: Integer;
begin
RestClient := TRESTClient.Create(nil);
try
RestClient.BaseURL := ‘localhost:3000’;
Request := TRESTRequest.Create(nil);
Request.Client := RestClient;
Request.Resource := ‘/users’;
Request.Method := rmGET;
Response := TRESTResponse.Create(nil);
Response.Request := Request;
Request.Response := Response;
Request.Execute;
Users := TJSONObject.ParseJSONValue(Response.Content) as TJSONArray;
try
for I := 0 to Users.Count — 1 do
begin
User := Users.Items[I] as TJSONObject;
// process user data here
end;
finally
Users.Free;
end;
Response.Free;
Request.Free;
finally
RestClient.Free;
end;
end;
This code retrieves a list of users from the API and loops through the JSON array to process each user. You can modify this code to retrieve other data from the API, or to perform other HTTP methods such as POST, PUT or DELETE.
In summary, building a RESTful API on your hosting and connecting to it from Delphi is a powerful way to create a scalable and maintainable database-driven application. By following the steps outlined in this post, you should be able to create a RESTful API and connect to it from your Delphi application using the TRESTClient and TRESTRequest components.