Create A Backend Server with APIs In Dart

Software Guide
4 min readJun 13, 2022

Hi Everyone, When you start creating a new product in the web and mobile space as a developer, you tend to get different choices to choose from for the development of UI and backend layer. As a developer, you try and get the best of the tech trends to make the product solid and efficient at the same time.

But sometimes, you may not get a resource who is proficient in the language you are looking for and at that time you may have to develop it yourself which may take a lot of time to market the product.

In Todays Article, we are gonna discuss about the implementation of the backend in Dart which can not only reduce your time to market if you are creating your UI but also a similar framework like a flutter and get more efficient as well. Although it may be in its nascent stage.

Table Of Contents.

  1. Setting up the project in Dart
  2. Creating and Running the Server
  3. Handling HTTP requests
  4. Creating Different Routing Endpoints
  5. Further Advanced Changes

Setting up the project in Dart

This is the first step we will be doing is by creating a project in dart. First of all, we need to install and configure Dart SDK in our system. Next, we need to install the below command in the specific folder where we are initiating the backend project in dart.

dart create [name_of_project]

You can open the project in your preferred IDE whether VS code or IntelliJ or any other.

Creating and running the Server

After following the step1 and creating a dart project and opening it in the IDE, we can start creating code for our project in the server file (which will be of the same name as your project name appended with .dart)

import 'dart:io';Future<void> main() async {
final server = await createBackendServer();
print('Server started at: ${server.address} and port ${server.port}');
}
Future<HttpServer> createBackendServer() async {
final address = InternetAddress.loopbackIPv4;
const port = 3000; //You can give port number you wish
return await HttpServer.bind(address, port);
}

This basic code snippet will start your dart backend server running at localhost(127.0.0.1) and port number as 3000 and you can see the console message being printed after you start the server.

Till now, You have created and set up your dart server. You can congratulate yourself now.

Handling HTTP requests

Now, the next step is handling the HTTP requests which are sent to this server from any external clients.

import 'dart:convert';
var requestAndResponseString= 'Hello From GET method from Dart';
Future<void> main() async {
final server = await createBackendServer();
print('Server started at: ${server.address} and port ${server.port}');
await handleHTTPRequests(server);
}
Future<void> handleHTTPRequests(HttpServer server) async {
await for (HttpRequest request in server) {
switch (request.method) {
case 'GET':
handleGetRequest(request);
break;
case 'POST':
handlePostRequest(request);
break;
}
}
}
void handleGetRequest(HttpRequest request) {
request.response
..write(requestAndResponseString)
..close();
}
Future<void> handlePostRequest(HttpRequest request) async {
requestAndResponseString= await utf8.decoder.bind(request).join();
request.response
..write('Succedded')
..close();
}
// Similar way other methods can be implemented

As you can see above, we have defined one new method from our previous step which is designed to handle requests coming to our server.

handleHTTPRequests method is used to handle requests coming from the client and responding.

Some key points with respect to the snippet shared above.

  1. As you can see there is a HTTPServer class that caters to different HTTPRequest coming in streaming format.
  2. If You call the API from any of the clients on a URL ie. http://localhost:3000, you will get to see the response defined above.
  3. We have used UTF-8 to format the incoming request and joined them in reading the request

Creating Different Routing Endpoints

void handleGetRequest(HttpRequest request) 
{
final path = request.uri.path;
switch (path) {
case '/resource1':
handleGetResource1(request);
break;
case '/resource2':
handleGetResource2(request);
break;
default:
handleGetOtherResources(request);
}
}
void handleGetResource1(HttpRequest request) {
request.response
..statusCode = HttpStatus.ok
..write('Resource1')
..close();
}
void handleGetResource2(HttpRequest request) {
request.response
..statusCode = HttpStatus.ok
..write(Resource2)
..close();
}
void handleGetOtherResource(HttpRequest request) {
request.response
..statusCode = HttpStatus.badRequest
..close();
}

As you can see, I defined different routing endpoints for the GET method i.e. /resource1 and /resource2, and for any other requests, I am responding back with a Bad Request message.

Further Advanced Changes

  1. There is a security context missing in the current implementation, we can add that as well, and that it will go one step closer to getting released in production.
  2. The second point is we can add versioning in all the routes and endpoints going forward which can enhance and make it better architecture friendly.

Conclusion

I hope this article will act as a good quick starter for all who are reading. And at the same time, will help them create backend servers in dart and it will reduce time to market if you are working and creating UI in Flutter.

Although Dart is in nascent stages as compared to Nodejs or any other backend servers/languages it has a lot of potential to grow further and solve a lot of different use cases.

--

--

Software Guide

This publication is regarding latest technology trends and a place where you can learn lot more about technology which is far beyond the books.