Getting Started with Dart, PostgreSQL, and Dart Frog: A Simple Guide
Dart is widely known for being the backbone of Flutter, but its capabilities go beyond building beautiful UIs. When combined with PostgreSQL and frameworks like Dart Frog, Dart becomes a powerful tool for creating backend services.
If you’re new to this ecosystem, don’t worry! In this article, we’ll explore how to connect Dart to PostgreSQL and build a simple backend API using Dart Frog — all explained in a friendly, beginner-friendly way. Let’s dive in!
Why Dart, PostgreSQL, and Dart Frog?
- Dart: Known for its simplicity and versatility, Dart is great for both front-end and back-end development. It offers strong typing, asynchronous support, and excellent performance.
- PostgreSQL: One of the most powerful and feature-rich relational databases out there. It’s open-source, reliable, and handles complex queries like a champ.
- Dart Frog: A lightweight, modern framework for building server-side applications with Dart. Think of it as the “Express.js for Dart,” but with Dart-specific goodies.
Let’s Build Something Cool!
In this guide, we’ll create a basic API that interacts with a PostgreSQL database to manage a “Tasks” table. You’ll be able to perform the following:
- Add new tasks.
- View all tasks.
Step 1: Setting Up the Project
First, make sure you have Dart installed on your system. If not, you can grab it from the official Dart site.
Then, install Dart Frog by running:
dart pub global activate dart_frog
Now, create a new Dart Frog project:
dart_frog create tasks_api
cd tasks_api
Step 2: Setting Up PostgreSQL
- nstall PostgreSQL on your system. (Check here for installation instructions.)
- Create a database and a table for tasks:
CREATE DATABASE tasks_db;
\c tasks_db
CREATE TABLE tasks (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
is_completed BOOLEAN DEFAULT FALSE
);
Step 3: Connect Dart to PostgreSQL
Add the postgres
package to your Dart Frog project. Open pubspec.yaml
and add:
dependencies:
postgres: ^2.7.0
Run dart pub get
to install the package.
Step 4: Write a Database Helper
Create a new file lib/db.dart
to handle database connections:
import 'package:postgres/postgres.dart';
class Database {
static final _connection = PostgreSQLConnection(
'localhost', // Host
5432, // Port
'tasks_db', // Database name
username: 'your_username', // Replace with your PostgreSQL username
password: 'your_password', // Replace with your PostgreSQL password
);
static Future<PostgreSQLConnection> getConnection() async {
if (_connection.isClosed) {
await _connection.open();
}
return _connection;
}
}
Step 5: Create the API Endpoints
- Open the
routes/
folder in your Dart Frog project.
- Replace the
routes/index.dart
file with this:
import 'dart:convert';
import 'package:dart_frog/dart_frog.dart';
import '../lib/db.dart';
Future<Response> onRequest(RequestContext context) async {
if (context.request.method == HttpMethod.get) {
return _getAllTasks();
} else if (context.request.method == HttpMethod.post) {
final body = await context.request.body();
final data = json.decode(body) as Map<String, dynamic>;
return _addTask(data['title']);
}
return Response(statusCode: 405); // Method not allowed
}
Future<Response> _getAllTasks() async {
final db = await Database.getConnection();
final result = await db.query('SELECT * FROM tasks');
final tasks = result.map((row) => {
'id': row[0],
'title': row[1],
'is_completed': row[2],
}).toList();
return Response.json(body: tasks);
}
Future<Response> _addTask(String title) async {
final db = await Database.getConnection();
await db.query('INSERT INTO tasks (title) VALUES (@title)', substitutionValues: {
'title': title,
});
return Response.json(body: {'message': 'Task added successfully'});
}
Step 6: Run Your API
Start your Dart Frog server:
dart_frog dev
Your API is now running at http://localhost:8080
. 🎉
Step 7: Testing the API
Add a Task
Use a tool like Postman or curl
to send a POST request:
curl -X POST http://localhost:8080 \
-H "Content-Type: application/json" \
-d '{"title": "Learn Dart Frog"}'
View All Tasks
Send a GET request:
curl http://localhost:8080
You should see something like this:
[
{
"id": 1,
"title": "Learn Dart Frog",
"is_completed": false
}
]
What’s Next?
Congratulations! 🎉 You’ve built a simple API using Dart, PostgreSQL, and Dart Frog. While this example is basic, it’s a strong foundation to build more advanced backend applications.