- Install Dart SDK: Make sure you have the Dart SDK installed. You can download it from the Dart SDK website.
- Install Aqueduct: Use the following command to install Aqueduct globally.
pub global activate aqueduct
Step 2: Create a New Aqueduct Project
- Create a new project:
aqueduct create my_aqueduct_app cd my_aqueduct_app
- Run the application:
aqueduct serve
Your server should now be running at http://localhost:8888
.
Step 3: Define Your Model
Create a model for your application. For example, let’s create a simple Task
model.
- Create a new model:In
lib/model/task.dart
, add the following code:
import 'package:aqueduct/aqueduct.dart'; class Task extends ManagedObject<_Task> implements _Task {} class _Task { @primaryKey int id; String title; bool completed; }
Step 4: Set Up Database Configuration
- Configure the database:In
config.yaml
, configure your database connection. For example, if you’re using PostgreSQL, it would look something like this:
database: host: localhost port: 5432 username: your_username password: your_password databaseName: your_database_name
- Migrate the database:Run the following command to create the database tables:bashCopy code
aqueduct db generate aqueduct db upgrade
Step 5: Create a Controller
Create a controller to manage the Task
model.
- Create a controller:In
lib/controller/task_controller.dart
, add the following code:
import 'package:aqueduct/aqueduct.dart'; import '../model/task.dart'; class TaskController extends ResourceController { TaskController(this.context); final ManagedContext context; @Operation.get() Future<Response> getAllTasks() async { final tasks = await context.fetch<Task>(); return Response.ok(tasks); } @Operation.post() Future<Response> createTask(@Bind.body() Task task) async { final insertedTask = await context.insertObject(task); return Response.ok(insertedTask); } }
Step 6: Set Up the Router
- Add the router:In
lib/my_aqueduct_app.dart
, set up the router to use yourTaskController
:
import 'package:aqueduct/aqueduct.dart'; import 'controller/task_controller.dart'; import 'model/task.dart'; class MyAqueductApp extends ApplicationChannel { @override Future prepare() async { // Database setup final config = DatabaseConfiguration(options["database"]); final database = PostgreSQLPersistentStore.fromConnectionInfo( config.username, config.password, config.host, config.port, config.databaseName); context = ManagedContext(dataModel, database); } ManagedContext context; @override Controller get entryPoint { final router = Router(); router.route("/tasks").link(() => TaskController(context)); return router; } }
Step 7: Test Your Application
- Run the server again:bashCopy code
aqueduct serve
- Use an API testing tool (like Postman or curl) to test your endpoints:
- GET all tasks:
curl http://localhost:8888/tasks
- Create a new task:
curl -X POST http://localhost:8888/tasks -H "Content-Type: application/json" -d '{"title": "My first task", "completed": false}'
Leave a Reply