Coder Social home page Coder Social logo

minimal-apis / minimal-apis.github.io Goto Github PK

View Code? Open in Web Editor NEW
64.0 2.0 19.0 22.97 MB

Tutorials and samples for ASP.NET Core Minimal APIs

Home Page: https://minimal-apis.github.io/

License: MIT License

Vue 11.13% JavaScript 74.51% Stylus 14.35%
aspnetcore minimalism minimalapi webapi dotnet csharp

minimal-apis.github.io's Introduction

deploy to gh-pages

minimal-apis.github.io

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.

minimal-apis.github.io's People

Contributors

bradygaster avatar davidfowl avatar dharmatech avatar glennc avatar halter73 avatar ievangelist avatar jcjiang avatar ladynaggaga avatar mairaw avatar rgwood avatar sonergonul avatar stevesandersonms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

minimal-apis.github.io's Issues

Tutorial Three: Cannot do first migration with EF Core migration tool

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:

  1. dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 6.0.0-preview.6.21352.1
  2. dotnet tool install --global dotnet-ef
  3. dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.0-preview.6.21352.1
  4. Set connection string
  5. Add context to services
  6. Run dotnet ef migrations add InitialCreate
  7. See logs

Expected behavior
I expect the migration to complete successfully
image

Screenshots
If applicable, add screenshots to help explain your problem.

image

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

OpenAPI + MinimalApis

What would you like see:

  • Documentation
  • Sample
  • Tutorial

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.

Setting request types in OpenAPIs

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);

HTTP Methods Overview in Quick Start

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!

Add a section that shows how concepts in other frameworks apply using minimal APIs

What would you like see:

  • Documentation
  • Sample
  • Tutorial

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:

Express

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();

Quick start - Content EPIC

What would you like see:

  • Documentation

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

Tutorial- Let's Build- Update and Item

`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");
}

}`

Update the ports in docs

Describe the bug
Currently, the ports are selected please update the docs on the website to reflect that. All the docs identify the 5001 and 5000 as the default ports.
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.