Code Monkey home page Code Monkey logo

azurefunctions.extensions's Introduction

As the Azure Functions OpenAPI Extension package was officially announced during the //Build event in May 2021, this repository has now been pivoted to maintain other extensions for Azure Functions.

If you have any questions around the OpenAPI extension, please pile up an issue to here.

AzureFunctions.Extensions

This provides some useful extensions for Azure Functions.

Getting Started Build and Test

Package Status Version
Aliencube.AzureFunctions.Extensions.Common

Packages for Reference Only

The following extensions are not actively developed any longer, but for reference only. You can find out the archived source codes by checking out the archived tag.

Package Status Version
Aliencube.AzureFunctions.Extensions.Configuration.AppSettings
Aliencube.AzureFunctions.Extensions.Configuration.Json
Aliencube.AzureFunctions.Extensions.DependencyInjection
Aliencube.AzureFunctions.Extensions.OpenApi.Core
Aliencube.AzureFunctions.Extensions.OpenApi
Aliencube.AzureFunctions.Extensions.OpenApi.CLI

Acknowledgement

Contribution

Your contributions are always welcome! All your work should be done in your forked repository. Once you finish your work with corresponding tests, please send us a pull request onto our dev branch for review.

License

AzureFunctions.Extensions is released under MIT License

The MIT License (MIT)

Copyright (c) 2018 aliencube.org

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

azurefunctions.extensions's People

Contributors

bpflugrad avatar filcole avatar glennular avatar gsteencg avatar hf-kklein avatar justinyoo avatar kelvinvm avatar kylednoland avatar lionhunter3k avatar mgranell avatar mkowalskigps avatar tsolbjor 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azurefunctions.extensions's Issues

Merging dev to master and cutting new nuget

Hello,

There is a bug which got fixed in dev but haven't made it to master (and nuget) yet - when (if?) is dev going to be merged to master and new nuget cut? Or should I fork the repo, merge/publish a different nuget?

DocumentHelper.cs - missing "Description" in swagger output

Your library is great! Thank you for putting it together. This function is missing Description = op.Description which causes a validation error when importing the swagger.json into Azure to create a Logic App Custom Connector. This is in the file DocumentHelper.cs around line 90.

 var operation = new OpenApiOperation()
                                {
                                    OperationId = string.IsNullOrWhiteSpace(op.OperationId) ? $"{function.Name}_{verb}" : op.OperationId,
                                    Tags = op.Tags.Select(p => new OpenApiTag() { Name = p }).ToList(),
                                    Summary = op.Summary,
                                    Description = op.Description
                                };

Support of multiple return types

On action with ability to return multiple results:
[OpenApiResponseBody(statusCode: ..., contentType: "...", bodyType: typeof(DataResponse))] [OpenApiResponseBody(statusCode: ..., contentType: "...", bodyType: typeof(ErrorResponse))] [OpenApiResponseBody(statusCode: ..., contentType: "...", bodyType: typeof(string))] [OpenApiResponseBody(statusCode: ..., contentType: "...", bodyType: typeof(string))]

I got error:
An unhandled host error has occurred. [7/25/2019 10:52:51 AM] Newtonsoft.Json: Unable to cast object of type 'App.Functions.Models.ErrorResponse' to type 'System.Collections.IEnumerable'.

My functions:
public async Task<IActionResult> GetAsync( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "data")] HttpRequest request) { ... if (!validation.IsValid) { return new BadRequestObjectResult(new ErrorResponse(validation.Errors)); } ... return new OkObjectResult(result); }

Generated error: operationId is repeated

This may or may not be a bug but since I cannot figure out if I am doing anything wrong I thought I'd create an issue so a solution can be shared.

I have a very simple app with two routes.

  • foo
  • foo/{id}

Why do I get this error generated in the Swagger UI?

{
  "messages": [
    "attribute paths.'/foo/{id}'(get).operationId is repeated"
  ]
}

An item with the same key has already been added. Key: ICollection

The document generation fails with the following exception:

An item with the same key has already been added. Key: ICollection.

I have traced this to the DocumentHelper class, GetOpenApiSchemas method.

When creating the dictionary of schemas, it uses as key either the type name or the underlying type name in case it's a generic type. This means that if you are returning ICollection and ICollection from 2 of your functions, they will both resolve to the ICollection key, and it will fail with the above exception.

Also, if you are returning NamespaceA.MyClass and NamespaceB.MyClass from 2 of your functions, they will both resolve to the MyClass key, and it will fail with the above exception.

The way Swashbuckle.AspNetCore.Swagger solves this, is by allowing you to specify a function to generate custom schema ids, something like this:

services.AddSwaggerGen(options =>
{
    options.CustomSchemaIds(x => x.FullName);
});

New JObject support is generating Swagger Error

I have pulled the latest code and see the Error iIincluded below, when expanding the method.

Related to #29

Errors
Resolver error at paths./samples/{id}/categories/{category}.get.responses.404.schema.$ref
Could not resolve reference: Could not resolve pointer: /definitions/JObject does not exist in document
Resolver error at paths./samples/{id}/categories/{category}.get.responses.500.schema.$ref
Could not resolve reference: Could not resolve pointer: /definitions/Dictionary`2 does not exist in document

image

Add support to multiple response type (support oneof, anyof, allof)

Swagger: https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/
Example: let us have two response definitons:

        public class CatResponse : AnimalResponse
        {
            public int MaxSpeed { get; set; }
        }

        public class BirdResponse : AnimalResponse
        {
            public int MaxFlightAttitude { get; set; }
        }

allow to do something like below where we can allow several types for response

[OpenApiResponseBody(
            HttpStatusCode.OK,
            "application/json",
            new[] {typeof(IList<CatResponse>), typeof(IList<BirdResponse>)},
            Description = "Return list of animals")]

How is AppSettings class implemented?

Can you explain or perhaps extend examples with the implementation of AppSettings? Since there is no such class on .NET Core it can be useful to provide the implementation.

Thank you for a great library.

Add a minimal sample

Your original blog post made things mostly simple but the samples you currently have rely on you needing DI and another project that is not a nuget just to add swagger. It seems overly complex just to add open API and swagger compared to the initial version.

I would have thought this could all be done with a single sample class that contains all needed functions and some nuget references. Bonus would be of a single nuget could add the class to the project and the references to the other nugets needed.

Does this expose itself to Logic Apps?

EDIT: Removed the questions that are only related to V1.

Will this automatically expose itself to Logic Apps? Maybe the endpoint in the function needs to have a special name?

Type List for OpenApiPayloadAttribute not mapped correctly

Hi,

I have a Function like this, returning a List<Product>:

[FunctionName("ListProducts")]
[OpenApiOperation("products", "Serverless Microservices")]
**[OpenApiResponseBody(HttpStatusCode.OK, "application/json", typeof(List<Product>))]**
public async Task<IActionResult> ListProducts...

The Product type looks like this:

public class Product
{
        public Guid Id { get; set; }
        public string Name { get; set; }
}

The JSON rendered for this response type is this:

{
  **"List`1"**: {
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "Id": {
          "format": "uuid",
          "type": "string"
        },
        "Name": {
          "type": "string"
        }
      }
    }
  }
}

... which is not really what I expected ;-)
Shouldn't there be a Product type and then a list/array of Product in the JSON?

Thanks!

DocumentHelper null check

As raised in the issue #8 , DocumentHelper needs null value handling.


var op = element.GetOpenApiOperation();
if(op == null)
{
    return new OpenApiOperation();
}

Swagger = how to get the value in path product/{id}/table/name

Hi
I am trying to get the value from the path product/{id}/table/name in swagger.

Code:
[OpenApiParameter("{id}", In = ParameterLocation.Path, Required = true, Type = typeof(string), Description = "product id", Visibility = OpenApiVisibilityType.Advanced)]

Open API document auth key auto assignment

Currently, OpenApi__ApiKey environment variable is required to access to the Open API document HTTP trigger. It would be handy if this API key can be internally fetched, rather than externally provided.

Working examples

I made a comment on your blogpost - not there anymore, perhaps you need to approve it first.

Just incase you miss it I will repeat it here.

I was unable to follow the instructions in this guide, ex. var settings = new AppSettings(); is that coming from the nuget package?

I then had a look at the Github project and while I was doing so a commit hit and changed things around. I cloned the repository and build Aliencube.AzureFunctions.FunctionAppCommon and Aliencube.AzureFunctions.Extensions.OpenApi and included both in my own project. Everything complies just fine if using the example from Github. I dot get an error when running the app

[2/11/2019 2:17:44 PM] Executed 'RenderSwaggerUI' (Failed, Id=65fbf008-1925-40f3-98b8-a70169927f8a)
[2/11/2019 2:17:44 PM] System.Private.CoreLib: Exception while executing function: RenderSwaggerUI. Aliencube.AzureFunctions.FunctionAppCommon: Method not found: 'System.Threading.Tasks.Task`1<Aliencube.AzureFunctions.Extensions.OpenApi.Abstractions.ISwaggerUI> Aliencube.AzureFunctions.Extensions.OpenApi.Abstractions.ISwaggerUI.BuildAsync()'.

If using the example from this post I get a compiler error at .BuildAsync(typeof(SwaggerUI).Assembly) as BuildAsync does not take any input. I can get it to compile if I do .BuildAsync().GetAwaiter().GetResult() but then I am back to the error from before.

Does the examples work with the latest nuget package, or am I missing something?

Looking forward to getting this to work, great work!

MissingMethodException Document.Build(Assembly, Newtonsoft.Json.Serialization.NamingStrategy)

Hello,

after just upgrading the NuGet package Aliencube.AzureFunctions.Extensions.OpenApi 1.5.4 from 1.5.2 (which was ok) I encountered following exception
requesting any of aliencube API (e.g. http://localhost:7071/api/openapi/v2.json)

MissingMethodException : Method not found: 'Aliencube.AzureFunctions.Extensions.OpenApi.Abstractions.IDocument Aliencube.AzureFunctions.Extensions.OpenApi.Abstractions.IDocument.Build(System.Reflection.Assembly, Newtonsoft.Json.Serialization.NamingStrategy)'

Note, that because of other project libs I needed to enforce Newtonsoft.Json version 11.0.1.

there is my NuGet packages spec in csproj

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.29" />
    <PackageReference Include="Microsoft.SharePointOnline.CSOM" Version="16.1.9021.1200" />
    <PackageReference Include="Newtonsoft.Json" Version="11.0.1" />
    <PackageReference Include="SharePointPnPCoreOnline" Version="3.12.1908" />
  </ItemGroup>
  <ItemGroup Condition="$(DefineConstants.Contains('OPEN_API_HTTPTRIGER'))">
    <PackageReference Include="Aliencube.AzureFunctions.Extensions.OpenApi" Version="1.5.4" />
  </ItemGroup>

As I have mentioned, the Aliencube.AzureFunctions.Extensions.OpenApi version 1.5.2 does not produce such an exception. So it is not critical for me - I just would like to inform you about it...

Swagger generation for JObject fails (due to IDictionary cast)

If a model class for an operation contains a JObject property (or JObject itself) the generation fails with an index out of bounds exception. I suppose this is linked to schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchema();(line 61 of OpenApiSchemaExtensions.cs) as JObject implements IDictionary but has no generic arguments itself.

I suggest either checking for JObject itself (as you are already referencing Newtonsoft.Json in that file) or checking if the count of arguments from GetGenericArguments exceeds 1.

Thanks
Joscha

Option to not include "function code" as default parameter

The current implementation of DocumentHelper includes "function code" as a parameter as long as the trigger does not have anonymous auth level.
I would be great if clients of the DocumentHelper could override this behavior as the function code is unwanted as part of the api doc in certain cases. We use this library on functions that we publish directly to api management were we have other authentication polices in place and does not expect the clients to know the function code

Annotate properties in request models

Is it possible to annotate properties in the request models to ex. describe if the property is mandatory or not. I think this is already in the OpenAPI spec.

No Content response

https://swagger.io/docs/specification/describing-responses/

Some responses, such as 204 No Content, have no body. To indicate the response body is empty, do not specify a content for the response:

responses:
        '204':
          description: The resource was deleted successfully.

If I try and provide [OpenApiResponseBody] with bodyType of null it throws a NullReferenceException.

Need a way to provide a response without content/schema for a No Content response.

Sample for doing auth for functions with "User" auth

It would be great to see a sample of how to do user auth using Azure AD for example. To do this currently I think you need to extend the formatter that is passed into the document but I am still playing to work it all out. It would be great if there was an easy way to configure it.

host.json' was not found and is not optional.

Hi, When i depoy the latest version of github, and deploy.
I get host.json' was not found and is not optional. when calling the swaggerui function.

2019-04-18T05:26:34 Welcome, you are now connected to log-streaming service.
2019-04-18T05:26:45.424 [Info] Function started (Id=57518a20-87d2-4da6-a8dd-c388b379057d)
2019-04-18T05:26:45.924 [Error] Exception while executing function: RenderSwaggerUI. Microsoft.Extensions.Configuration.FileExtensions: The configuration file 'host.json' was not found and is not optional. The physical path is 'D:\local\Temporary ASP.NET Files\root\e359b4f0\f82c3575\assembly\dl3\67deff64\host.json'.
2019-04-18T05:26:46.033 [Error] Function completed (Failure, Id=57518a20-87d2-4da6-a8dd-c388b379057d, Duration=601ms)

OpenApiParameter with enum type not rendered correctly

Using

[OpenApiParameter("x-my-enum-header" In = ParameterLocation.Header, Type = typeof(MyEnum))]

with

public enum MyEnum
{
   ONE_OPTION,
   ANOTHER_OPTION
}

leads to an OpenApi-Json:

"schema": {
    "type": "integer",
    "format": "int32"
},

but should render as

"enum": {
    "ONE_OPTION"
    "ANOTHER_OPTION"
},

and thus allow the use of ONE_OPTION or ANOTHER_OPTION in the Swagger UI instead of just integer values.

DateTimeOffset in OpenApiRequestBody causes StackOverflowException when rendering JSON

When providing type for OpenApiRequestBodyAttribute in constructor, if the type has DateTimeOffset as one of the fields, an attempt to render the JSON causes StackOverflowException.

Sample function with such request type:

 [OpenApiRequestBody("application/json", typeof(FakeRequestType))]
        public static async Task<IActionResult> UpdateDelivery(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req,
            ILogger logger)
{
....
}

public class FakeRequestType
{
      public string DeliveryId { get; set; }
      public DateTimeOffset DateWithOffset { get; set; }
 }

Sample JSON render:

   [FunctionName(nameof(RenderJson))]
        [OpenApiIgnore]
        public static async Task<IActionResult> RenderJson(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger.json")]
            HttpRequest req, ILogger log)
        {
            try
            {
                var settings = new AppSettings();
                var helper = new DocumentHelper(new RouteConstraintFilter());
                var document = new Document(helper);
                var result = await document.InitialiseDocument()
                    .AddMetadata(settings.OpenApiInfo)
                    .AddServer(req, settings.HttpSettings.RoutePrefix)
                    .Build(Assembly.GetExecutingAssembly())
                    .RenderAsync(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json)
                    .ConfigureAwait(false);
                var response = new ContentResult
                {
                    Content = result,
                    ContentType = "application/json",
                    StatusCode = (int) HttpStatusCode.OK
                };

                return response;
            }
            catch (Exception e)
            {
                log.LogError(e, "Error while rendering OpenApi json.");
                throw;
            }
        }

Schema response body generation doesn't work with Lists and Generics

The response bodies for Generic T's are not handled correctly. When you have for instance a PagedViewModel<MessageViewModel> class then the schema will not be generated into the OpenApi definitions.

Take for example this functions definition

[FunctionName("Get_Messages")]
[OpenApiOperation("get_paged_messages", "messages")]
[OpenApiResponseBody(HttpStatusCode.OK, "application/json", typeof(PagedViewModel<MessageViewModel>))]
public static async Task<HttpResponseMessage> GetMessages(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "messages")] HttpRequestMessage req)
{
...
}

The generated OpenAPI definition is this:

"/messages": {
    "get": {
        "tags": [
            "messages"
        ],
        "operationId": "get_paged_messages",
        "responses": {
            "200": {
                "description": "Payload of PagedViewModel`1",
                "content": {
                    "application/json": {
                        "schema": {
                            "$ref": "#/components/schemas/PagedViewModel`1"
                        }
                    }
                }
            }
        }
    }
},

"components": {
    "securitySchemes": {
        "authKey": {
            "type": "apiKey",
            "name": "x-functions-key",
            "in": "header"
        }
    }
}

The schemas property in the components is missing. Same goes for using List or IENumerable. Seems only to work for flat objects.

Sbyte datatype in model causes swagger rendering to fail

First of all, thanks for this nuget. This helps certainly to document the Azure function api's.

When i try it out found that if the model has the datatype as SByte, it causes Swagger rendering to fail with the below error, bool works.

Are there any restriction if so why?

any help on this one would be really helpful.

image

Model Definition:
public class Bet
{
[JsonProperty("id")]
public sbyte Id { get; set; }
}

OpenApiResponseBody attribute with body type CreatedResult throws

[OpenApiResponseBody(HttpStatusCode.Created, "application/json", typeof(CreatedResult), Summary = "CreatedResult object response.")]

Log:

Executing 'RenderSwaggerDocument' (Reason='This function was programmatically called via the host APIs.', Id=xxxx)
Process is terminating due to StackOverflowException.

TargetFramework: netcoreapp2.2
AzureFunctionsVersion: v2
OpenApi: v1.5.4

Swagger file generation fails for arrays

Aliencube.AzureFunctions.Extensions.OpenApi version: 1.3.0

When request DTOs contain arrays the following error gets thrown:

[13.02.2019 13:16:28] Executed 'RenderSwaggerDocument' (Failed, Id=fb5e9696-1da8-4267-a434-696e6b1fad40) [13.02.2019 13:16:28] System.Private.CoreLib: Exception while executing function: RenderSwaggerDocument. Aliencube.AzureFunctions.Extensions.OpenApi: Index was outside the bounds of the array.

Example request dto:

    public class RequestDto
    {
        public int[] Array { get; set; }
    }

Example function:

        [FunctionName(nameof(Run))]
        [OpenApiOperation("add", "sample")]
        [OpenApiRequestBody("application/json", typeof(RequestDto))]
        [OpenApiResponseBody(HttpStatusCode.OK, "application/json", typeof(string))]
        public static async Task<ActionResult<string>> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "") ] RequestDto poco)
        {
            return string.Empty;
        }

My RenderSwaggerDocument function:

        [FunctionName(nameof(RenderSwaggerDocument))]
        [OpenApiIgnore]
        public static async Task<IActionResult> RenderSwaggerDocument([HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger.json")]
            HttpRequest req)
        {
            var helper = new DocumentHelper();
            var document = new Document(helper);
            var result = await document.InitialiseDocument()
                                       .AddMetadata(new OpenApiInfo { Title = "My API", Version = "v1" })
                                       .AddServer(req, "api")
                                       .Build(Assembly.GetExecutingAssembly())
                                       .RenderAsync(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json)
                                       .ConfigureAwait(false);
            var response = new ContentResult()
            {
                Content = result,
                ContentType = "application/json",
                StatusCode = (int)HttpStatusCode.OK
            };

            return response;
        }

AddScoped behaves like Singleton

Sample project: https://github.com/Planche95/AddScopedSample

public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddScoped(typeof(Foo));
            builder.Services.AddTransient(c => GetBar(c));
        }

        private Bar GetBar(IServiceProvider prov)
        {
            var foo = prov.GetService<Foo>();

            return new Bar(foo);
        }
    }

prov.GetService(); always gets the same instance of Foo.

public class Bar
    {
        private readonly Foo _please;

        public Bar(Foo please)
        {
            _please = please;
        }
    }

Foo _please; is also always the same instance.

public class Function1
    {
        private readonly Foo _foo;
        private readonly Bar _bar;
        public Function1(Foo foo, Bar bar)
        {
            _foo = foo;
            _bar = bar;
        }

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
        {
            return new OkObjectResult($"Hello");
        }
    }

looks like only inside Function Scoped working correctly.


Wrong Repo, my bad!

AddLogger method for IFunction<TLogger>

it currently accepts logger through property injection. Instead of doing that, it can be added through method and chain it like:

var result = await new MyFunction()
                       .AddLogger<ILogger>(log)
                       .InvokeAsync<HttpRequest, IActionResult>(req)
                       .ConfigureAwait(false);

By doing so, the function can be used for both instance methods and static methods.

Section SecurityRequirements is missing

When added security scheme's SwaggerUI also requires a security section that references to the security scheme like:

"securityDefinitions": {
	"authKey": {
		"type": "apiKey",
		"name": "x-functions-key",
		"in": "header"
	}
},
/* missing : */
"security": [
        {
            "authKey": []
        }
}

As a result the entered authentication is NOT applied when executing the call's. (in this case; the x-function-key missing in the header of the request).
The fix is easy add the following to the Document.Build(..)

 if (_document.Components.SecuritySchemes != null ||
    _document.Components.SecuritySchemes.IsEmpty())
{
    var securityRequirement = new OpenApiSecurityRequirement();
    foreach (var securitySchemeId in _document.Components.SecuritySchemes.Keys)
    {
        var key = new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Id = securitySchemeId,
                Type = ReferenceType.SecurityScheme
            }
        };
        securityRequirement.Add(key, new string[0]);
    }
    _document.SecurityRequirements.Add(securityRequirement);
}

AppSettings class used on docs page not available

On the docs page for: Aliencube.AzureFunctions.Extensions.OpenApi

unable to find any namespaces that include the reference to AppSettings:

var settings = new AppSettings();

All other references are resolved. Is there another nuget package to include?

Auto-add functions to expose swagger/doc

It would be very useful when adding the nuget package Aliencube.AzureFunctions.Extensions.OpenApi that it automatically added functions for RenderOpenApiDocument and RenderSwaggerUI.

This would make it a lot easier to add this to existing projects instead of cloning the sample functions and merging with existing code.

  • Add nuget
  • Annotate
  • Run
  • :-)

Support constraints in route

When generating OpenApi/Swagger for my Azure Functions I noticed that your library does not support routes with constraints in the interpolation.
Route = "product/{id:int}

I decorate the method with:
[OpenApiParameter("id", In = ParameterLocation.Path, Required = true, Type = typeof(int))]

But in SwaggerUI the route displays as .../product/{id:int} instead of expected .../product/{id}.
Also "Try it out" does not replace the path parameter when send ing the request to the function, resulting in a 404 response.

Sample doesn't compile

The OpenAPI sample states that we have to add this function to get a SwaggerUI

[FunctionName(nameof(RenderSwaggerUI))]
[OpenApiIgnore]
public static async Task<IActionResult> RenderSwaggerUI(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger/ui")] HttpRequest req,
    ILogger log)
{
    var settings = new AppSettings();
    var ui = new SwaggerUI();
    var result = await ui.AddMetadata(settings.OpenApiInfo)
                         .AddServer(req, settings.HttpSettings.RoutePrefix)
                         .BuildAsync(typeof(SwaggerUI).Assembly)
                         .RenderAsync("swagger.json", settings.SwaggerAuthKey)
                         .ConfigureAwait(false);
    var response = new ContentResult()
                       {
                           Content = result,
                           ContentType = "text/html",
                           StatusCode = (int)HttpStatusCode.OK
                       };

    return response;
}

However BuildAsync doesn't accept arguments, and yields a Task which should be awaited. It should be:

[FunctionName(nameof(RenderSwaggerUI))]
[OpenApiIgnore]
public static async Task<IActionResult> RenderSwaggerUI(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger/ui")] HttpRequest req,
    ILogger log)
{
    var settings = new AppSettings();
    var ui = new SwaggerUI();
    var swaggerUI = await ui.AddMetadata(settings.OpenApiInfo)
                            .AddServer(req, settings.HttpSettings.RoutePrefix)
                            .BuildAsync()
                            .ConfigureAwait(false);

    var result = await swaggerUI.RenderAsync("swagger.json")
        .ConfigureAwait(false);

    var response = new ContentResult()
    {
        Content = result,
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK
    };

    return response;
}

Enum ToDataType method overly restrictive

It looks like the ToDataType method in EnumExtensions prevents things like byte-backed Enums from working in generated swagger doc. Is there a design reason from this, or could it be added to the number switch cases?

Give Ability to Configure Security Scheme

It would be nice to be able to define a different OpenApiSecurityScheme on the root of the DocumentHelper other than "x-functions-key".
This would add support for custom bearer auth, for example.
See DocumentHelper.cs line 172

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.