Your first API
In this tutorial, you build the REST API of a small catalog: categories, their products, and the photos of the products. You write the entities, models, DTOs, filters, and validators, and Magicalizer does the rest. It takes about 15 minutes.
The complete code is in the GettingStarted sample.
Create the project
Create an empty web application and add the packages (see Installation):
dotnet new web -o App
cd App
dotnet add package Magicalizer
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.AspNetCore.OpenApi
The classes go to the folders of their layers: Data/Entities, Domain/Models, Api/Dto, Api/Dto/Validators, and
Filters. The folders and namespaces are only a convention: Magicalizer finds the classes wherever they are.
1. Entities
The entities are the classes of Entity Framework Core. To be used by Magicalizer, an entity implements IEntity, whose
type arguments are the types of its primary key properties (in the order of the primary key).
using Magicalizer.Data.Entities.Abstractions;
namespace App.Data.Entities;
public class Category : IEntity<int>
{
public int Id { get; set; }
public string? Name { get; set; }
public virtual ICollection<Product>? Products { get; set; }
}
The database context is configured as usual:
using Microsoft.EntityFrameworkCore;
namespace App.Data.Entities;
public class AppDbContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Photo> Photos { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>(etb => {
etb.HasKey(e => e.Id);
etb.ToTable("Categories");
});
modelBuilder.Entity<Product>(etb => {
etb.HasKey(e => e.Id);
etb.ToTable("Products");
});
modelBuilder.Entity<Photo>(etb => {
etb.HasKey(e => e.Id);
etb.ToTable("Photos");
});
base.OnModelCreating(modelBuilder);
}
}
2. Program
Register the database context as DbContext, add Magicalizer and the OpenAPI description:
using App.Data.Entities;
using Magicalizer.Extensions;
using Microsoft.EntityFrameworkCore;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DbContext, AppDbContext>(options => {
options.UseSqlite(builder.Configuration.GetConnectionString("Default"));
});
builder.Services.AddMagicalizer();
builder.Services.AddOpenApi();
WebApplication webApplication = builder.Build();
// The database is created on the first run (use the migrations of EF Core in a real application).
using (IServiceScope scope = webApplication.Services.CreateScope())
scope.ServiceProvider.GetRequiredService<DbContext>().Database.EnsureCreated();
webApplication.UseMagicalizer();
webApplication.MapOpenApi();
webApplication.Run();
Add the connection string to appsettings.json:
{
"ConnectionStrings": {
"Default": "Data Source=app.db"
}
}
Tip
EnsureCreated creates the database on the first run, which is handy for a tutorial. A real application uses the
migrations of Entity Framework Core instead.
3. Models
The models are the domain layer, the one the services work with. A model implements IModel, whose type arguments
are its entity and its filter (you create the filters in step 5). It’s created from its entity by the constructor that
takes the entity, and it’s converted back by ToEntity.
using Magicalizer.Domain.Models.Abstractions;
namespace App.Domain.Models;
public class Category : IModel<Data.Entities.Category, Filters.CategoryFilter>
{
public int Id { get; set; }
public string? Name { get; set; }
public IEnumerable<Product>? Products { get; set; }
public Category() { }
public Category(Data.Entities.Category categoryEntity) : this(categoryEntity, ignoreProducts: false) { }
public Category(Data.Entities.Category categoryEntity, bool ignoreProducts)
{
this.Id = categoryEntity.Id;
this.Name = categoryEntity.Name;
if (!ignoreProducts)
this.Products = categoryEntity.Products?.Select(p => new Product(p, ignoreCategory: true, ignorePhotos: false)).ToList();
}
public Data.Entities.Category ToEntity()
{
return new Data.Entities.Category {
Id = this.Id,
Name = this.Name
};
}
}
Note the ignore... parameters. The related entities refer to each other: the products of an included category refer
to it, and it refers to them. So the related models leave out the references back (a product of a category is
created with ignoreCategory: true), otherwise the conversion would never end.
When a related entity isn’t loaded, the model still keeps its primary key (new Category { Id = ... }), so the
reference isn’t lost on an update.
4. DTOs
The DTOs are the contract of the API: what the clients send and get. A DTO implements IDto, whose type argument is
its model, and it’s marked with [Magicalized], which sets the route of its API. Like a model, it’s created from its
model by the constructor and converted back by ToModel.
using Magicalizer.Api.Dto.Abstractions;
namespace App.Api.Dto;
[Magicalized("v1/categories")]
public class Category : IDto<Domain.Models.Category>
{
public int Id { get; set; }
public string? Name { get; set; }
public IEnumerable<Product>? Products { get; set; }
public Category() { }
public Category(Domain.Models.Category categoryModel) : this(categoryModel, ignoreProducts: false) { }
public Category(Domain.Models.Category categoryModel, bool ignoreProducts)
{
this.Id = categoryModel.Id;
this.Name = categoryModel.Name;
if (!ignoreProducts)
this.Products = categoryModel.Products?.Select(p => new Product(p, ignoreCategory: true, ignorePhotos: false)).ToList();
}
public Domain.Models.Category ToModel()
{
return new Domain.Models.Category {
Id = this.Id,
Name = this.Name
};
}
}
Each [Magicalized] DTO gets a controller with the list, get by the primary key, create, update, JSON Patch, and delete
actions.
5. Filters
A filter describes how the objects can be filtered. Each of its properties filters the entity property with the same
name: a value filter (e.g. StringFilter), the filter of a related entity, or EnumerableFilter of a collection.
using Magicalizer.Filters.Abstractions;
namespace App.Filters;
public class CategoryFilter : IFilter
{
public IntegerFilter? Id { get; set; }
public StringFilter? Name { get; set; }
public EnumerableFilter<ProductFilter>? Products { get; set; }
}
A property that isn’t in the filter can’t be filtered by: the request is rejected (see Errors).
6. Validators
The validators are the usual FluentValidation ones. The validators of the DTOs run in the API, the validators of the
models (none here) run in the services. The rules without a rule set are checked always, the ones of
RuleSetName.Create and RuleSetName.Edit only on creation and editing.
using FluentValidation;
using Magicalizer.Validators.Abstractions;
namespace App.Api.Dto.Validators;
public class CategoryValidator : AbstractValidator<Category>
{
public CategoryValidator()
{
this.RuleFor(c => c.Name).NotEmpty().MaximumLength(64);
this.RuleSet(RuleSetName.Edit, () => {
this.RuleFor(c => c.Id).NotEmpty();
});
}
}
7. Run
Run the application:
dotnet run
Magicalizer logs the APIs it has created:
info: Magicalizer[0]
The magicalized DTO Category is served by MagicalizedController<Category> at /v1/categories: GET, POST, PUT, PATCH, DELETE.
info: Magicalizer[0]
The magicalized DTO Photo is served by MagicalizedController<Photo> at /v1/photos: GET, POST, PUT, PATCH, DELETE.
info: Magicalizer[0]
The magicalized DTO Product is served by MagicalizedController<Product> at /v1/products: GET, POST, PUT, PATCH, DELETE.
info: Magicalizer[0]
3 controllers are created for the magicalized DTOs.
If a DTO is missing from the list, see Startup diagnostics.
8. Try the API
Send the requests with any HTTP client. The sample has them in GettingStarted.http, which Visual Studio, Rider, and VS Code (with the REST Client extension) run right from the editor.
Create
POST /v1/categories
Content-Type: application/json
{"name": "Pizza"}
HTTP/1.1 201 Created
Location: /v1/categories/1
{"id": 1, "name": "Pizza", "products": null}
Create a second category, Sushi, a few products, and a photo the same way (the .http file has all of them):
POST /v1/products
Content-Type: application/json
{"category": {"id": 1}, "name": "Margherita", "price": 9.5}
A product refers to its category by the primary key. A category that doesn’t exist ({"id": 99}) is reported as an
error of the request, not of the server:
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Category": ["The referenced model with the primary key (99) doesn't exist."]
}
}
Validate
The validators run before anything is saved, and all the errors come at once:
POST /v1/products
Content-Type: application/json
{"category": {"id": 1}, "name": "", "price": 0}
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Name": ["'Name' must not be empty."],
"Price": ["'Price' must be greater than '0'."]
}
}
Query
Filter, sort, and page the lists with the query parameters:
GET /v1/products?category.name.equals=Pizza&sort=-price
[
{"id": 2, "category": {"id": 1, "name": null, "products": null}, "name": "Quattro Formaggi", "price": 12.0, ...},
{"id": 1, "category": {"id": 1, "name": null, "products": null}, "name": "Margherita", "price": 9.5, ...}
]
The related objects aren’t loaded unless they are included (the category has only its primary key above). Include them, the nested ones too:
GET /v1/categories/1?include=products.photos
{
"id": 1,
"name": "Pizza",
"products": [
{"id": 1, "name": "Margherita", "price": 9.5, "photos": [{"id": 1, "filename": "margherita.jpg", ...}], ...},
{"id": 2, "name": "Quattro Formaggi", "price": 12.0, "photos": [], ...}
]
}
The lists are paged by offset and limit, and the total count comes in the headers:
GET /v1/products?sort=name&offset=0&limit=2
HTTP/1.1 200 OK
Paging-Total-Count: 3
Paging-Offset: 0
Paging-Limit: 2
A mistake in a query is never ignored silently: all of them are reported.
GET /v1/products?naem.contains=pep&sort=colour
{
"status": 400,
"errors": {
"sort": ["Unable to sort by 'colour': the type 'Product' doesn't have the property 'colour'."],
"naem.contains": ["The query parameter isn't supported."]
}
}
Update and delete
PUT replaces an object, PATCH changes a part of it with a JSON Patch (mind its content
type), and DELETE deletes it. All three return 204 No Content, or 404 Not Found when the object doesn’t exist.
PUT /v1/categories
Content-Type: application/json
{"id": 2, "name": "Sushi and rolls"}
PATCH /v1/categories/2
Content-Type: application/json-patch+json
[{"op": "replace", "path": "/name", "value": "Rolls"}]
DELETE /v1/photos/1
See the description
The OpenAPI description of the API, with all the filter conditions, is at /openapi/v1.json. Open it in any OpenAPI
viewer (e.g. add Scalar or Swagger UI to the application), or generate a client
from it.
What you’ve built
With 16 small classes and no controllers, services, or query code, the application has:
- 3 REST APIs with 6 actions each;
- filtering by the properties, the related objects, and the collections, as well as sorting and paging;
- the inclusion of the related objects;
- the validation and the errors as problem details;
- the OpenAPI description.
Next steps
- A layered solution: split the classes into the projects of their layers.
- HTTP API: everything the clients can do with the API.
- Building blocks: the entities, models, DTOs, filters, and validators in depth.
- Customization: your own services, controllers, and prefilters.