csharpfritz / instantapis Goto Github PK
View Code? Open in Web Editor NEWA library that generates Minimal API endpoints for an Entity Framework context.
License: MIT License
A library that generates Minimal API endpoints for an Entity Framework context.
License: MIT License
I have a .NET 6 project, but I'm using Program.cs
and 'Startup.cs' approach.
There is a method to add InstantAPI using services.AddInstantAPIs();
, but no way to configure it inside Configure(IApplicationBuilder app)
https://github.com/csharpfritz/InstantAPIs/blob/main/Fritz.InstantAPIs/WebApplicationExtensions.cs#L18 supports IEndpointRouteBuilder
but a method that supports IApplicationBuilder
is missing.
Any plans to add support for it?
Introduce Action
parameters on configuration that optionally allow injection of methods to be triggered before the data interaction and after the data interaction
by invoking the Set
method of the base class.
I'm creating a pull request for the readme and MyContext.cs
Great ideas with this library! Thanks!
Tagging @softchris for visibility
Added configuration support to choose entities from JSON file
Tagging @softchris for visibility
Define an IRepository interface and support mapping a concrete instance of that to APIs
This will help support other data providers
It would be cool if there’s filtering & sorting
Add the ability to generate services from @softchris dev.to article
https://dev.to/dotnet/how-you-can-build-a-mock-api-based-on-json-for-asp-net-and-minimal-api-1dmd
I have looked at several .csproj files and they all use Spaces for indentation.
It might be a good idea to put an .editorconfig file in that ensures that only Tabs instead of Spaces are used for indentations.
It would be nice if this whole process could be like a pluggable pipeline (kind of like middleware) where I can just slot in additional functionality. So initial example would just be to add a fluent validator based on each db model and use attributes like [Required] or [MaxLength(500)] to hint to the validation rules that will apply for that object.
public class MyClass
{
[Required]
public string Name { get; set; }
[MaxLength(500)]
public string Description { get; set; }
}
public class MyClassValidator : AbstractValidator<MyClass>
{
public MyClassValidator()
{
RuleFor(request => request.Name)
.Must(x => !string.IsNullOrWhiteSpace(x))
.WithMessage(x => "Name is required!");
RuleFor(request => request.Description)
.MaximumLength(500)
.WithMessage(x => "Description must be less than 500 characters!");
}
}
Tagging @softchris for visibility
We should enable optional gRPC bindings with an entry in the InstantAPI configuration
Methods should return appropriate 200, 201, 404, etc HTTP status codes for their interactions
It might be nice if the user was allowed to inherit their model from an IModel
interface that looked something like this:
interface IModel
{
int/Guid Id { get; set;}
}
This would allow the code not to have to use the Type.GetProperty()
method and provide more IntelliSense.
It'd be a good enhancement to configure it with a mapper to map database model to view model and vice versa.
Mappers like Automapper
As of now, (correct me if I'm wrong) InstantAPIs supports creating all API endpoints (HTTP GET, GET by ID, POST, PATCH, PUT, and DELETE) or just one. It might be nice if it allowed the user to customize which ones they create. For example, a user might only want HTTP GET and DELETE endpoints.
We should enable optional GraphQL support with an entry in the InstantAPI configuration
This version can separate the apis by group? As when we use the .WithTags() parameter in out minimal apis, then Swagger group the routes above a title inside the .WithTags().
e.g:
app.MapInstantAPIs(config =>
{
config.IncludeTable(db => db.TABLE1, ApiMethodsToGenerate.All, "TABLE1").WithTags("GROUP TABLE 1");
});
app.MapInstantAPIs(config =>
{
config.IncludeTable(db => db.TABLE2, ApiMethodsToGenerate.All, "TABLE2").WithTags("GROUP TABLE 2");
});
Swagger will show something like this:
GROUP TABLE 1
[GET] /TABLE1
[POST] /TABLE1
[GET] /TABLE1/{id}
[PUT] /TABLE1/{id}
[DELETE] /TABLE1/{id}
GROUP TABLE 2
[GET] /TABLE2
[POST] /TABLE2
[GET] /TABLE2/{id}
[PUT] /TABLE2/{id}
[DELETE] /TABLE2/{id}
I love the idea behind this project. This is great and I am looking forward to this becoming more mature, stable and famous!
The following configuration options might be required in a lot of cases:
Thanks,
Raghu
It would be great to be able to enable OpenAPI configuration for the APIs using the InstantAPI configuration
Design to come
We need to allow authentication and authorization to be configured.
We should enable Authorization with optional entries in the InstantAPI configuration
_from @bravecobra's post on #49
[ ] allow authorization for the generated APIs and be able to specify authenticated users, required policies, etc...
It's great to have it already available on NuGet :-)
I think the version number should have a text included, such as preview, beta, alpha, such as *0.1.0-preview.1.4242.
With a text in the version number, the package is only shown when selecting include prerelease, and not leads to production quality.
Suppose I have this class
`
public class Food : Record
{
public string Name { get; set; }
public decimal Portion { get; set; }
public decimal Calories { get; set; }
public decimal Carbohydrates { get; set; }
public decimal Lipids { get; set; }
public decimal Proteins { get; set; }
public decimal Fiber { get; set; }
public Guid SourceId { get; set; }
public Source Source { get; set; }
public Classification Classification { get; set; }
public NewClassification NewClassification { get; set; }
public ICollection<FoodRecipes> FoodRecipes { get; set; }
}
`
When using InstantAPIs, the following swagger body model is created
{ "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "registration": "2023-09-04T02:26:10.760Z", "update": "2023-09-04T02:26:10.760Z", "deletion": "2023-09-04T02:26:10.760Z", "name": "string", "portion": 0, "calories": 0, "carbohydrates": 0, "lipids": 0, "proteins": 0, "fiber": 0, "sourceId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "source": { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "registration": "2023-09-04T02:26:10.760Z", "update": "2023-09-04T02:26:10.760Z", "deletion": "2023-09-04T02:26:10.760Z", "name": "string" }, "classification": 0, "newClassification": 0, "foodRecipes": [ { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "registration": "2023-09-04T02:26:10.760Z", "update": "2023-09-04T02:26:10.760Z", "deletion": "2023-09-04T02:26:10.760Z", "recipeId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "recipe": { "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "registration": "2023-09-04T02:26:10.760Z", "update": "2023-09-04T02:26:10.760Z", "deletion": "2023-09-04T02:26:10.760Z", "name": "string", "foodRecipes": [ "string" ] }, "foodId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "food": "string" } ] }
I wish there would be a way to provide custom DTOs and maybe using AutoMapper to transforming to entity class, like
app.MapInstantAPIs<EuNutroContext>(config => { config.ExcludeTable(db => db.AnyTable); config.UseCustomDto(db => db.Food, typeof(AddFoodDto), ApiMethodsToGenerate.Insert); // like this });
When using the fluent interface and not marking your keys with the [Key] annotation and those keys are not named "id" then the _IdLookup dictionary will not be filled with the keys for the entity.
This is due to MapApiExtensions having id hard coded into it. I wonder if it would be easy to add a configuration option to define how the property is matched? For example {ClassName}Id or {ClassName}_Id
I did a quick proof of concept by adding the following code in line 26 of MapApiExtensions:
var theType = typeof(C);
var keyName = $"{theType.Name}Id";
var idProp = theType.GetProperty("id", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) ??
theType.GetProperty(keyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) ??
theType.GetProperties().FirstOrDefault(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)));
Anyone can help find out why im getting this error?
KeyNotFoundException: The given key 'dbContext.DataModel.Models.AspNetUserLogin' was not present in the dictionary.
Here is part of my Program.cs
builder.Services.AddSqlServer<dbContext>(builder.Configuration.GetConnectionString("DefaultConnectionLocal"));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddApplicationInsightsTelemetry();
builder.Services.AddInstantAPIs();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
// Use CORS
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.MapInstantAPIs<dbContext>();
app.Run();
I think the MapInstantAPIs method could be implemented with a source generator. This might also make it easier to create customizations with partial methods.
What do you think?
Introduce configuration to allow mapping from the datasource to a ViewModel, and mapping from the ViewModel to the datasource
Using Automapper may be the preferred technique here
Using EntityFrameworkCore we can map an entity to multiple tables or multiple entities to a single table (TPT, TPH etc)
This made me wonder about the usage of nouns like “table” and “column” (when configuring IncludeTable/ExcludeTable). Perhaps a better and more consistent fit with EFCore domain language would be “entity” (or “entity type”) and “property”.
Hence IncludeEntity/ExcludeEntity instead…?
There is not always a one to one mapping regards entity to table.
Add entries to the standard ASP.NET Core log that reflect the Map methods created and their URL endpoints.
Perhaps a verbose logging experience should also declare the data access method attached to the URL
In the Contributing document there is a broken link to the Code-of-Conduct document. This is related to issue #20
Hello, is there an option to export the endpoints generated to a log or a class
file for us to view or generate a menu
context, or generic Ajax caller
Let's put together a docs folder along with a GitHub action to generate a docs site to live on the ghpages branch and GitHub static site that goes with this repository.
We should also add a link/shield to the README that points to the docs site
Needs a test project
Validation and model binding for the POST and PUT operations are needed
I was trying to generate Minimal APIs for the Northwind database. I generated the entities with dotnet ef scaffold
command with data annotation support. After scaffolding some entities generated with Keyless
attribute.
[Keyless]
public partial class CategorySalesFor1997
{
[StringLength(15)]
public string CategoryName { get; set; } = null!;
[Column(TypeName = "money")]
public decimal? CategorySales { get; set; }
}
When I run the application - MapInstantAPIs
failed with KeyNotFoundException
.
I think we should skip the tables with the Keyless
attribute.
Need to configure individual APIs with documentation for OpenAPI
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.