Skip to content

Build a blog API

This tutorial takes you from an empty folder to a small blog API that runs as one native binary.

Each step has the full code and a curl command to check your work. The finished project is on GitHub: examples/blog-api. CI builds it and runs its tests on each push.

What you will build

A JSON API for blog posts. Anyone can read posts. Only a logged in user can write them:

Method Path Who What it does
GET /api/posts anyone list all posts
GET /api/posts/{id} anyone one post, or 404
POST /api/posts logged in user make a post (201, or 422 on bad input)
PUT /api/posts/{id} logged in user change a post
POST /api/auth/register anyone make an account, get a token
POST /api/auth/login anyone log in, get a token
GET /api/auth/user logged in user the user of the token

What you need

  • Dart 3.13 or newer. Check it with dart --version.
  • curl, to call the API.
  • Approximately 15 minutes.

You do not need Docker or a database server. The app uses SQLite, which keeps the database in one file in your project.

The steps

  1. Create the project
  2. Model and migration
  3. Routes and controller
  4. Validation
  5. Authentication
  6. Test
  7. Build and deploy

The finished project

This is the project at the end. A * marks the files that you make or change. The template has more files, but this tree shows only the files of this tutorial.

blog/
├── bin/
│   ├── migrate.dart              runs the dox migration:* commands
│   ├── server.dart               runs the migrations, starts the server
│   └── queue.dart, schedule.dart, seed.dart
├── db/migration/
│   ├── ..._create_posts_table.dart   *
│   ├── ..._create_users_table.dart
│   └── migrations.dart           the list of migrations (Dox writes it)
├── lib/
│   ├── app/http/controllers/
│   │   ├── auth.controller.dart  *
│   │   └── post.controller.dart  *
│   ├── app/dtos/
│   │   ├── login_user/login_user.dto.dart   *
│   │   ├── register_user/register_user.dto.dart *
│   │   └── save_post/save_post.dto.dart    *
│   ├── app/models/
│   │   ├── post/post.model.dart  *
│   │   └── user/user.model.dart
│   ├── config/
│   │   ├── app.dart              * adds the DTO list
│   │   ├── database.dart
│   │   └── env.dart              the .env keys, typed
│   ├── routes/api.dart           *
│   ├── providers/
│   │   ├── auth_provider.dart    *
│   │   └── orm_provider.dart
│   └── generated/
│       ├── container.g.dart      * generated
│       └── dtos.g.dart           * generated
├── test/http_test.dart           *
├── .env                          made by dox create
├── Dockerfile
└── pubspec.yaml                  * adds dox_auth

Next steps