Web Analytics Made Easy -
StatCounter
create-apis-with-dart-frog-backend-server-for-dart-flutter

A backend server calledDart Frogis developed in Dart and intended to be scalable, quick, and reliable.
In this article, we will learnhow to use dart frog to create API. Theflutter developerscan use the Dart Frog backend server to create API using dart.

Install dart_forg_cli

Open the terminal and run the below command

dart pub global activate dart_frog_cli

Create a new Dart Frog Project

Open the terminal and run the below command

dart_frog create name_of_project such as dart_frog create dart_frog_apis_ammarjavedofficial

Open the Dart Frog project

I’ll open the project in VSCode because I’ll be using VSCode throughout the article on How to create APIs with dart frog a backend server.

Start the Dart Frog backend server

In the VSCode open the terminal and run the below command

dart_frog dev

or we can run the server on the port of our choice using the below command

dart_frog dev --port 7878

Connecting with Database

I’ll use MySQL database for storing the data in the database. That’s why I’ll use XAMPP to run the Apache server and MySQL database.
In the VSCode terminal execute the below command

dart pub add mysql_client

The mysql_client package will help us to connect with the MySQL database.

In theprojectfolder, create a new folderlib. In the lib folder create a folderdatabase. In the database folder, create a new filemysql_client.dart.
Open the mysql_client.dart file and paste the below code to have a connection with the database.

import 'package:mysql_client/mysql_client.dart';


///

class MySQLClientConnection {


  ///

  factory MySQLClientConnection() {

    return _inst;

  }


  MySQLClientConnection._internal() {

    _connectDatabase();

  }


  static final MySQLClientConnection _inst = MySQLClientConnection._internal();


  MySQLConnection? _connection;


  ///

  Future _connectDatabase() async {

    _connection = await MySQLConnection.createConnection(

      host: 'localhost',

      port: 3306,

      userName: 'root',

      password: '1234',

      databaseName: 'crud',

      secure: false,

    );

    await _connection?.connect();

  }


  ///

  Future runQuery(

    String query, {

    Map? params,

    bool iterable = false,

  }) async {

    if (_connection == null || _connection?.connected == false) {

      await _connectDatabase();

    }


    if (_connection?.connected == false) {

      throw Exception('Could not connect to the database');

    }

    return _connection!.execute(query, params, iterable);

  }


  ///

  bool? get checkDatabaseConnection {

    return _connection?.connected;

  }
}

TheconnectDatabasemethod is used to connect with the MySQL Database and therunQuerymethod is used to execute the MySQL query and for checking database connectivity.
The gettercheckDatabaseConnectionmethod is used to check if the database is running or not.

Checking Database Connectivity with the API EndPoint

In theprojectfolder, create a filemain.dartand in the main.dart file paste the below code for the database initialization.

import 'dart:io';

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/database/mysql_client.dart';


final mySQLClientConnection = MySQLClientConnection();


Future run(Handler handler, InternetAddress ip, int port) {

  return serve(handler.use(databaseHandler()), ip, port, poweredByHeader: 'Dart Frog Apis - AmmarJavedOfficial',);

}


Middleware databaseHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => mySQLClientConnection,

      ),

    );

  };

}

Now open the routes folder and in theindex.dartfile paste the below code.

import 'package:dart_frog/dart_frog.dart';


import '../main.dart';


Future onRequest(RequestContext context) async {

  if (context.request.method.name == 'get') {

    try {

      return Response.json(

        body: mySQLClientConnection.checkDatabaseConnection == true

            ? 'Connection Successfully'

            : 'Connection Unsuccessful',

      );

    } catch (error) {

      return Response(body: error.toString());

    }

  } else {

    return Response.json(

      body: {

        'error':

            '${context.request.method.name.toUpperCase()} Method Not Supported'

      },

    );

  }

}

Run thehttp://localhost:7878API endpoint in the postman to check whether the database connection is successful or not.

Check Database Connectivity - Dart Frog API

Creating a Model folder

Inside thelibfolder create a new foldermodelsand inside the models folder create a new fileusers_model.dartand paste the below code.

///

class UsersModel {


  ///

  factory UsersModel.fromJson(Map json) {

    return UsersModel(

      userId: json['userId'] as String,

      userName: json['userName'] as String,

      userPassword: json['userPassword'] as String,

    );

  }  


  ///

  factory UsersModel.databseRow(Map json) {

    return UsersModel(

      userId: json['userId'],

      userName: json['userName'],

      userPassword: json['userPassword'],

    );

  }


  ///

  Map toJson() {

    return {

      'userId': userId,

      'userName': userName,

      'userPassword': userPassword,

    };

  }


  ///

  UsersModel({

    this.userId,

    this.userName,

    this.userPassword,

  });


  ///id

  final String? userId;


  ///userName

  final String? userName;


  ///password

  final String? userPassword;
}

We will beusing the methodsinside the UsersModel class in order to handle the JSON data.

Creating a Controller folder

Inside thelibfolder create new foldercontrollersand inside the controllers folder create a new fileusers_controller.dartand paste the below code.

import 'package:dart_frog_apis_ammarjavedofficial/database/mysql_client.dart';

import 'package:dart_frog_apis_ammarjavedofficial/models/users_model.dart';


///

class UsersController {

  ///

  UsersController(this._mySQLClientConnection);


  final MySQLClientConnection _mySQLClientConnection;


  ///

  Future> postUserCreate({

    required String? userName,

    required String? userPassword,

  }) async {

    await _mySQLClientConnection.runQuery(

      "INSERT INTO `users_table`(`userName`, `userPassword`) VALUES ('$userName','$userPassword')");

    return {

      'success': 'User Created',

    };

  }


  ///

  Future> getAllUsersList() async {

    final items = [];

    final result = await _mySQLClientConnection.runQuery(

        'SELECT * from users_table',);

    for (final row in result.rows) {

      items.add(UsersModel.databseRow(row.assoc()));

    }

    return items;

  }


  ///

  Future> getUserDetailsById(

        {

      String? userId

    }

  ) async {

    final result = await _mySQLClientConnection

        .runQuery("SELECT * FROM `users_table` WHERE userId = $userId");

    if (result.numOfRows != 0) {

      return result.rows.first.assoc();

    } else {

      return {'error': "User Don't Exists"};

    }

  }  


  ///

  Future> patchUserUpdate({

    String? userId,

    required String? userName,

    required String? userPassword,

  }) async {

    final result = await _mySQLClientConnection.runQuery(

      "UPDATE `users_table` SET `userName`='$userName',`userPassword`='$userPassword' WHERE userId = $userId");

    if (result.affectedRows != BigInt.from(0)) {

        return {'success': 'User Updated'};

    } else {

      return {'error': "User Don't Exists"};

    }    

  }  


  ///

  Future> deleteUserDelete(

    {

      String? userId

    }

  ) async {

    final result = await _mySQLClientConnection

        .runQuery('DELETE FROM `users_table` WHERE userId = $userId;');

    if (result.affectedRows != BigInt.from(0)) {

      return {

        'success': 'User Deleted',

      };

    } else {

      return {'error': "User Don't Exists"};

    }

  }


  ///

  Future> deleteAllUsers(

  ) async {

    final result = await _mySQLClientConnection

        .runQuery("DELETE FROM `users_table`");

    if (result.affectedRows != BigInt.from(0)) {

      return {

        'success': 'Users Deleted',

      };

    } else {

      return {'error': "Users Don't Exists"};

    }

  }

}

We will be using themethodsinside theUsersController classto execute theSQL queriesin order to get the list of all users, and detail of a specific user, update a user, create a new user, and delete users.

Create a User using the API endPoint

In theroutes folder, create a new folderusers.
In theusers foldercreate afolder PostUserCreateand in the PostUserCreate folder create afile _middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for dependency Injection.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };

}

In theindex.dartfile paste the below code in order to have accessto the UsersController class object and to create a new user using the API endpoint.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context,) async {

  final usersMiddleware = context.read();

  if (context.request.method.name == 'post') {

    final userName = context.request.uri.queryParameters['userName'];

    final userPassword = context.request.uri.queryParameters['userPassword'];


    if(userName != null && userPassword != null)

    {

    try {

      final users = await usersMiddleware.postUserCreate(

        userName: userName,

        userPassword: userPassword,

      );

      return Response.json(body: users);

    } catch (error) {

      return Response(body: error.toString());

    }

    } else {

      return Response.json(body: {'error' : 'All Parameters Are Required'});

    }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }

}

Now in the Postman run thehttp://localhost:7878/users/PostUserCreate?userName=AmmarJavedOfficial&userPassword=123456789API endpoint tocreate a new user.

PostUserCreate - Dart Frog API

Get a List of Users using the API endPoint

In theusers folder,create a folderGetAllUsersand in the GetAllUsers folder create afile _middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for returning the instance of UsersController class.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };

}

In theindex.dartfile paste the below code in order to have accessto the UsersController class instance and to fetch all users from the database.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context) async {

  final usersMiddleware = context.read();


  if (context.request.method.name == 'get') {

    try {

      final users = await usersMiddleware.getAllUsersList();

      if (users.isEmpty) {

        return Response.json(

          body: {

            'error': 'No User Exists',

          },

        );

      } else {

        return Response.json(

          body: users,

        );

      }

    } catch (error) {

      return Response(body: error.toString());

    }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }

}

Now in the Postman run thehttp://localhost:7878/users/GetAllUsersAPI endpoint to get thelist of all users.

GetAllUsers - Dart Frog API

Get User Details using the API endPoint

In theusers folder,create a folderGetUserDetailsand in the GetUserDetails folder create a file_middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for returning the instance of UsersController class.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };

}

In theindex.dartfile paste the below code in order to have accessto the UsersController class instance and to fetch all users from the database.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context) async {

  final usersMiddleware = context.read();

  if (context.request.method.name == 'get') {

  final userId = context.request.uri.queryParameters['userId'];

  if (userId!.isNotEmpty) {

    try {

      final users = await usersMiddleware.getUserDetailsById(

        userId: userId,

      );

      return Response.json(

        body: users,

      );

    } catch (error) {

      return Response(body: error.toString());

    }

  } else {

    return Response.json(

      body: {

        'error': 'User Id is Required',

      },

    );

  }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }
}

Now in the Postman run thehttp://localhost:7878/users/GetUserDetails?userId=1API endpoint to get thedetails of a user.

GetUserDetails - Dart Frog API

Update User Details using the API endPoint

In theusers folder,create a folderPatchUserUpdateand in the PatchUserUpdate folder create a file_middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for dependency injection using the provider.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };

}

In theindex.dartfile paste the below code in order to have accessto the UsersController class instance and to update the details of a specific user by id.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context,) async {

  final usersMiddleware = context.read();


  if (context.request.method.name == 'patch') {

    final userId = context.request.uri.queryParameters['userId'];

    final userName = context.request.uri.queryParameters['userName'];

    final userPassword = context.request.uri.queryParameters['userPassword'];

    if(userId != null)

    {

    try {

      final users = await usersMiddleware.patchUserUpdate(

        userId: userId,

        userName: userName,

        userPassword: userPassword,

      );

      return Response.json(body: users);

    } catch (error) {

      return Response(body: error.toString());

    }

    } else {

      return Response.json(body: {'error' : 'User Id is Required'});

    }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }

}

Now in the Postman run thehttp://localhost:7878/users/PatchUserUpdate?userName=AJOfficial&userPassword=123456API endpoint toupdate a user.

PatchUserUpdate - Dart Frog API

Delete a Specific User using the API endPoint

In theusers folder,create a folderDeleteUserDeleteand in the DeleteUserDelete folder create a file_middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for dependency injection using the provider.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };

}

In theindex.dartfile paste the below code in order to have accessto the UsersController class instance and to delete a specific user by id.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context, String userId) async {

  final usersMiddleware = context.read();


  if (context.request.method.name == 'delete') {

    try {

      final users = await usersMiddleware.deleteUserDelete(

        userId: userId,

      );

      return Response.json(body: users);

    } catch (error) {

      return Response(body: error.toString());

    }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }
}

Now in the Postman run thehttp://localhost:7878/users/DeleteUserDelete/1API endpoint todelete a user.

DeleteUserDelete - Dart Frog API

Deleting All Users using the API endPoint

In theusers folder,create a folderDeleteAllUsersand in the DeleteAllUsers folder create a file_middleware.dartandindex.dart.
In the_middleware.dartfile paste the below code for dependency injection using the provider.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


import '../../../main.dart';


Handler middleware(Handler handler) {

  return handler.use(requestLogger()).use(injectionHandler());

}


Middleware injectionHandler() {

  return (handler) {

    return handler.use(

      provider(

        (context) => UsersController(mySQLClientConnection),

      ),

    );

  };
}

In theindex.dartfile paste the below code in order to have accessto the UsersController class instance and to delete all users.

import 'package:dart_frog/dart_frog.dart';

import 'package:dart_frog_apis_ammarjavedofficial/controllers/users_controller.dart';


Future onRequest(RequestContext context) async {

  final usersMiddleware = context.read();


  if (context.request.method.name == 'delete') {

    try {

      final users = await usersMiddleware.deleteAllUsers();

      return Response.json(body: users);

    } catch (error) {

      return Response(body: error.toString());

    }

  } else {

    return Response.json(

      body: {'error': '${context.request.method.name.toUpperCase()} Method Not Supported'},

    );

  }

}

Now in the Postman run thehttp://localhost:7878/users/DeleteAllUsersAPI endpoint todelete all users.

DeleteAllUsers - Dart Frog API

Source Files

GitHub

https://github.com/ammarjavedofficial/dart_frog_apis_ammarjavedofficial

Database File

https://drive.google.com/file/d/17kbftHpF3DO7ttLP9N6_GEXmMBsr8PCo/view?usp=sharing

Postman JSON File

https://drive.google.com/file/d/1F5rlSBWGFUzVyMWeRmekX76jiSTOUiG2/view?usp=sharing

Conclusion

In this article, we get to knowhow to create APIs using dart frog package.

Avatar

By AmmarJaved

Ammar Javed possesses a unique combination of skills and expertise in web, desktop, and mobile app development, and content writing. Ammar Javed is a strategic thinker and has problem-solving abilities. Ammar Javed can work independently and in a team. Ammar Javed is dedicated to continuous learning and professional development.

Leave a Reply

Your email address will not be published. Required fields are marked *