Tutorials and samples for minimal APIs.
- To run the site locally, navigate minimal-apis.github.io to and run -
npm run dev
. - To add or update docs, go to
src
folder. - To add or update menu items, go to the
src/.vuepress/config.js
file.
Tutorials and samples for ASP.NET Core Minimal APIs
Home Page: https://minimal-apis.github.io/
License: MIT License
Please let me know if I am missing something on my end, but I wanted to note that when I tested out the 'Returning HTML' section, nothing pops up for me. I copied the code on the website and pasted it to my project in VS Code, and I keep getting the Webpage error message.
<img width="951" alt="Screen Shot 2021-10-03 at 5 49 49 PM" src="https://user-images.githubusercontent.com/71569075/135779503-0db6b404-3e9d-4f1e-b333-176e8dc1fa33.png"
The current quick start page to something more meaningful to the user https://minimal-apis.github.io/quickstart/
Works in progress samples
https://github.com/Minimal-APIs/samples/tree/main/React
What would you like see:
What would you like see:
Endpoints defined via minimal APIs can be annotated with metadata for use in OpenAPI libraries with a series of extension methods.
You can set the EndpointName
or EndpointGroupName
of an endpoint using the WithName
and WithGroupName
extension methods as follows.
string SomeFoo() => "This is a string.";
app.MapGet("/foo", SomeFoo).WithName("MyEndpointName").WithGroupName("EndpointName");
Note: If you have multiple WithName
statements on the same endpoint, the last endpoint will be favored.
On the topic of endpoint names, by default, endpoints that use a method group or named lambda will have their endpoint name set to the method name. For example, in the code snippet below, the endpoint will have a default endpoint name of SomeFoo
.
string SomeFoo() => "This is a string.";
app.MapGet("/foo", SomeFoo);
This default endpoint name can be overloaded by using the WithName
extension method as referenced above.
string SomeFoo() => "This is a string.";
app.MapGet("/foo", SomeFoo).WithName("MyOwnSpecialName");
To omit an endpoint from being displayed in API metadata, you can use the ExcludeFromDescription
extension method on the endpoint.
app.MapGet("/foo", () => { .. }).ExcludeFromDescription();
OK, but let's say that you did want an endpoint to be annoted. In addition to endpoint names, you can also use the various ProducesX
endpoints to indicate the response types of a method. The available extension methods are:
Produces<TResponse>(int statusCode = 200, string? contentType = "application/json", params string[] additionalContentTypes)
Produces(int statusCode = 200, System.Type? responseType = null, string? contentType = "application/json", params string[] additionalContentTypes)
ProducesProblem(int statusCode, string? contentType = "application/problem+json")
ProducesValidationProblem(int statusCode = 400, string? contentType = "application/validationproblem+json")
So, in general, the Produces
extension methods give you the flexibility to set a ProblemDetails
response type for your endpoint or define what response it returns on happy-path scenarios. You can do this with the generic-typed implementation Produces<TResponse>
or with the Produces
attribute. So, for example, to define the response metadata for a POST method that returns a Todo
or a ProblemDetails
response you can annotate it using the following extension methods.
app.MapPost("/todos", (Todo todo) => { ... })
.ProducesProblem(401)
.Produces<Todo>(201);
Note: ProducesProblem
is the only extension method that doesn't set a status code by default. This allows you to make the right choices about what the most detailed status code for the scenarios in your API is, as opposed to using a generic 500 status code.
In addition to setting the type of data that is produced as the response in an endpoint, we can also document what data an endpoint takes as endpoint using the Accepts
extension method.
For example, to document that a method accepts a Todo
type in an application/json
payload would be documented as follows.
app.MapPost("/todos", (Todo todo) => { ... })
.Accepts<Todo>("application/json")
.ProducesProblem(401)
.Produces<Todo>(201);
`using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddDbContext(options => options.UseInMemoryDatabase("items"));
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Todo API", Description = "Keep track of your tasks", Version = "v1" });
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Todo API V1");
});
app.MapGet("/", () => "Hello World!");
app.MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync());
app.MapPost("/todos", async (TodoDb db, TodoItem todo) =>
{
await db.Todos.AddAsync(todo);
await db.SaveChangesAsync();
return Results.Created($"/todo/{todo.Id}", todo);
});
app.MapGet("/todos/{id}", async (TodoDb db, int id) => await db.Todos.FindAsync(id));
app.MapPut("/todos/{id}", async ( TodoDb db, TodoItem updateTodo ,int id) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return NotFound();
todo.Item = updateTodo.Item;
todo.IsComplete = updateTodo.IsComplete;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.Run();
class TodoItem
{
public int Id { get; set; }
public string? Item { get; set; }
public bool IsComplete { get; set; }
}
class TodoDb : DbContext
{
public TodoDb(DbContextOptions options) : base(options) { }
public DbSet Todos { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("Todos");
}
}`
This should basically be an up-to-date version of dotnet/aspnetcore#30248 that goes over the parameter binding sources, attributes, inference, TryParse
, BindAsync
, etc...
Captured here #36
What would you like see:
What kind of content are you looking for ?
We should have a section on the site that lists a couple of top level concepts in various frameworks (routing, middleware, logging, dependency injection (where applicable)), as a way to quickly get somebody that is already using an existing framework up to speed with similar concepts in minimal.
For example:
Routes
// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage')
})
app.MapGet("/", () => "GET request to the homepage");
app.MapPost("/", () => "POST request to the homepage");
Route parameters
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
app.MapGet("/users/{userId}/books/{bookId}", (int userId, int bookId) => {
return new { userId, bookId };
});
Middleware
var express = require('express')
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
var app = WebApplication.Create(args);
app.Use((context, next) =>
{
Console.WriteLine($"Time: {DateTime.Now}");
return next(context);
});
StaticFiles
var express = require('express')
var app = express()
app.use(express.static('public', options))
var app = WebApplication.Create(args);
app.UseStaticFiles();
Apps I want to or are currently building
Minimal APIs with existing apps
I tried out the following code provided in the doc
app.MapGet("/hello", () => "Hello World!");
app.MapGet("/todos", () => new { TodoItem = "Learn about routing", Complete = false });
app.MapPost("/todos", () => Result.Ok());
And I received the following error message-
(6,29): error CS0103: The name 'Result' does not exist in the current context
Just want to make note of that!
What would you like see:
What kind of content are you looking for ?
What would you like see:
[ ] Documentation
[ ] Sample
[ ] Tutorial
What kind of content are you looking for ?
What would you like see:
To be written up
Describe the bug
In Tutorial Three: Add a Database, I run into an error when I run dotnet ef migrations add InitialCreate
.
To Reproduce
Steps to reproduce the behavior:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 6.0.0-preview.6.21352.1
dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.0-preview.6.21352.1
Expected behavior
I expect the migration to complete successfully
Screenshots
If applicable, add screenshots to help explain your problem.
Desktop (please complete the following information):
What would you like see:
This issue is intended to capture the content needed for the minimal APIs quick start. These quick starts are designed to provide developers with a brief overview of features and a how-to guide to different parts of minimal APIs. The TOC listed isn't in priority
What kind of content are you looking for ?
More topics
For inspiration please looks at
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.