Giter VIP home page Giter VIP logo

nancy.swagger's Introduction

Nancy.Swagger Build status

Nancy plugin for generated API documentation in Swagger format.

The Swagger specification (v2.0) can be found here.

Documentation

Documentation for Nancy.Swagger can be found in the wiki pages

NuGet Packages

Versions 2.2.0+ of this code uses Nancy v2 and is designed for .NET 4.5.2 and .NET Standard 1.6.

Version 2.1.1 is designed for Nancy v1.4.3 on .Net 4.0+, and creates a Swagger 2.0 document.

Version 0.* is designed for Nancy v1.4.3, but creates a Swagger 1.2 document.

  • If for some reason you need to make a change against this version of Nancy.Swagger, you can checkout the 1.4.3-stable branch.

The code in this repository contains the code for the following NuGet packages:

How to Contribute

Simply fork/clone this repository and start making whatever improvements you want! We'll try to make sure there are 'newbie' tickets available for those looking to start contributing.

CI NuGet Feed

The CI NuGet feed can be found at https://www.myget.org/F/nancy-swagger/

nancy.swagger's People

Contributors

bespokebob avatar catcherwong avatar goodmorninggoaway avatar jchannon avatar jnallard avatar jonnyhweiss avatar jvrdev avatar khellang avatar liddellj avatar lucasmoffitt avatar seekiong-appspace avatar timschlechter avatar vincentparrett avatar yahehe 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

nancy.swagger's Issues

Avoid dependency on Newtonsoft.Json

Personally I'm not keen on taking a dependency on Newtonsoft.Json if it could be avoided.

  1. It's strongly named.
  2. It's strongly named.
  3. Might cause issues for people who already reference an alternate serialization package in their Nancy project?

Unless I'm missing something - and this isn't a problem?

Since Nancy now supports camelCasing JSON out-of-the-box, seems like we could almost use the default serializer, if it weren't for those dang properties in the Swagger API called $ref - which I see your handling with [JsonProperty("$ref")].

Thoughts?

Json a bit odd with list property

I'm not sure if this is correct or not, if you have a model that has a property that is a List it produces the below JSON which I think is correct but in the swagger-ui it shows the below. I guess it appears like that as the Participant type and its properties are not included in the raw JSON. Maybe if it did it wouldnt appear odd in the UI. Thoughts?

properties: {
  Participants: {
    type: "array",
    items: {
      $ref: "Participant"
    },
  }
},

capture

An item with the same key has already been added.

Hit this, this afternoon:

An item with the same key has already been added.

System.ArgumentException: An item with the same key has already been added.
  at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
  at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
  at Nancy.Swagger.Services.SwaggerMetadataConverter.GetApiDeclaration(String resourcePath)
  at Nancy.Swagger.Modules.SwaggerModule.<>c__DisplayClass9.<.ctor>b__6(Object _)
  at CallSite.Target(Closure , CallSite , Func`2 , Object )
  at Nancy.Routing.Route.<>c__DisplayClass4.<Wrap>b__3(Object parameters, CancellationToken context)

Here are the two Nancy routes:

// /api/foo as base
            Get["AvailableFoos", "/available"] = AvailableFoos;
            Get["AvailableFoosByLocation", "/available-by-locations"] = AvailableFoosByLocation;

Here's the two Swagger calls:

            Describe["AvailableFoos"] = description => description.AsSwagger(with =>
            {
                with.ResourcePath("/api/foo");
                with.ApiPath("/api/foo/available");
                with.Summary("Returns a list of available Foo");
                with.Notes("This returns a list of available Foo");
                with.Response(200, "Foo data");
                with.Response(401, "Unauthorized");
                with.QueryParam("filter", "Filter", required: false, defaultValue: "");
                with.QueryParam<int?>("customerId", "Customer Id", required: false, defaultValue: 0);
                with.QueryParam<bool?>("allow", "Allow", required: false, defaultValue: false);
                with.QueryParam<string>("selected", "CSV list of selected Ids to exclude from results", required: false, defaultValue: "");
                with.Model<string>(); // don't ask...
            });

            Describe["AvailableFoosByLocation"] = description => description.AsSwagger(with =>
            {
                with.ResourcePath("/api/foo");
                with.ApiPath("/api/foo/available-by-locations");
                with.Summary("Returns a list of available Foo by location");
                with.Notes("This returns a list of Foo by location");
                with.Response(200, "Foo data");
                with.Response(401, "Unauthorized");
                with.QueryParam<int?>("customerId", "Customer Id", required: false, defaultValue: 0);
                with.QueryParam<TimeZoneInfo>("timeZone", "TimeZone"); // TODO: Hmm. Can't be nullable but is optional...
                with.QueryParam<DateTime>("startTime", "Start Time");
                with.QueryParam<DateTime>("stopTime", "Stop Time");
                with.QueryParam<string>("locations", "CSV list of selected locations", required: false, defaultValue: "");
                with.Model<List<FooLocationViewModel>>();
            });
        }

I've been through and confirmed that there are no named routes with the same name but I'm confused as to how this is breaking Swagger?

Edit:
After some debugging and getting the actual source code I see the exception occurs here:
https://github.com/khellang/Nancy.Swagger/blob/master/src/Nancy.Swagger/Services/SwaggerMetadataConverter.cs#L40

Annotations attribute naming

In #17 it became clear the attribute names used to describe routes and models where somewhat ambiguous. We decided to reduce the nr of attributes and give them very explicit names like SwaggerRoute, SwaggerRouteParam, SwaggerModel. The idea here was tom simplify the interface and make it as explicit as possible. We could always rename or add subclasses later.

I've opened this issue to have a place to write down ideas and discuss the naming.

Some ideas:

  • just get rid of the Swagger prefix, resulting in
  • Route
  • RouteParam
  • RouteResponse
  • Model
  • ModelProperty
  • Prefix with Api, like the Apache CXF implementation does. Resulting in
    • ApiRoute
    • ApiRouteParam
    • ApiRouteResponse
    • ApiModel
    • ApiModelProperty

A Nancy API returning anonymous types is difficult to document with Nancy.Swagger

I modified Nancy.Swagger.Demo to add the following endpoint:

Get["GetUserRole", "/userrole"] = _ => new {User = new User {Name = "Vincent Vega", Age = 45}, Role = "Admin"};

and then tried to document it. The metadata module isn't too bad:

Describe["GetUserRole"] = description => description.AsSwagger(with =>
{
    with.ResourcePath("/userrole");
    with.Summary("Gets a User and role");

    var exemplar = new {User = (User) null, Role = (string) null};
    with.GetType().GetMethod("Model").MakeGenericMethod(exemplar.GetType()).Invoke(with, new object[0]);
});

But trying to work out how to implement ISwaggerModelDataProvider.GetModelData() is challenging.
I'm not interested in making my Nancy code less dynamic by creating static types for all models.

Is there something I'm missing?

Does this run with the Nancy v2.0.0 version?

Getting the following error:

[MissingMethodException: Method not found: 'Void Nancy.Bootstrapper.Registrations..ctor()'.]
Nancy.Swagger.SwaggerRegistrations..ctor() +0
lambda_method(Closure , Object[] ) +42
Nancy.TinyIoc.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options) +682

[TinyIoCResolutionException: Unable to resolve type: Nancy.Swagger.SwaggerRegistrations]
Nancy.TinyIoc.TinyIoCContainer.ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options) +717
Nancy.TinyIoc.SingletonFactory.GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) +123
Nancy.TinyIoc.TinyIoCContainer.ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options) +85
Nancy.TinyIoc.TinyIoCContainer.b__138_2(TypeRegistration registration) +32
System.Linq.WhereSelectEnumerableIterator2.MoveNext() +164 System.Linq.<CastIterator>d__941.MoveNext() +54
System.Collections.Generic.List1..ctor(IEnumerable1 collection) +333
System.Linq.Enumerable.ToList(IEnumerable1 source) +58 Nancy.Bootstrapper.NancyBootstrapperWithRequestContainerBase1.RegisterRegistrationTasks(IEnumerable1 registrationTasks) +52 Nancy.Bootstrapper.NancyBootstrapperBase1.Initialise() +366
Nancy.Hosting.Aspnet.NancyHttpRequestHandler..cctor() +26

[TypeInitializationException: The type initializer for 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler' threw an exception.]
Nancy.Hosting.Aspnet.NancyHttpRequestHandler..ctor() +0

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +114
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1088
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +128
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +20
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +60
System.Web.Configuration.HandlerFactoryCache..ctor(String type) +46
System.Web.HttpApplication.GetFactory(String type) +86
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +224
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

QueryParam int required issue

Given a route with:

Get["ListFoo", "/"] = ListFoo;
protected dynamic ListFoo(dynamic parameters)
    {
        var customerId = Request.Query.customerId.TryParse<int>(0);
        var filter = Request.Query.filter.TryParse<string>("");
        var includeExternal = Request.Query.includeExternal.TryParse<bool>();

        return FooService.List(customerId, filter, includeExternal);
    }

And the Swagger documentation like:

        Describe["ListFoo"] = description => description.AsSwagger(with =>
        {
            with.ResourcePath("/api/foo");
            with.ApiPath("/api/foo");
            with.Response(200, "Foo List");
            with.Response(401, "Unauthorized");
            with.QueryParam("filter", "Filter", required: false, defaultValue: "");
            with.QueryParam<int>("customerId", "Customer Id", required: false, defaultValue: 0);            
            with.QueryParam("includeExternal", "Include External", required: false, defaultValue: false);
            with.Model<List<FooListViewModel>>();
        });

The "customerId" parameter is shown as required in the Swagger UI, the workaround we eventually discovered is to set it like:

with.QueryParam<int?>("customerId", "Customer Id");       

And it is no longer shown as required.

Does this seem correct?

ISwaggerModelDataProvider properties not visible in UI

If I have something along the lines of

 public class UserModelDataProvider : ISwaggerModelDataProvider
    {
        public SwaggerModelData GetModelData()
        {
            return SwaggerModelData.ForType<User>(with =>
            {
                with.Description("A user of our awesome system!");
                with.Property(x => x.Name)
                    .Description("The user's name")
                    .Required(true);
                with.Property(x => x.Age)
                    .Description("The user's age")
                    .Required(true)
                    .Minimum(1)
                    .Maximum(100);
            });
        }
    }

The description of the users age shows and shows it as not optional but the values of 1 and 100 do not.

Is it supposed to?

Upgrade Nancy.Swagger to stable release

Nancy.Swagger is currently in pre-release as the Nancy 2.0 dependency is also in pre-release. After Nancy 2.0 is upgraded to stable we should do the same.

Action to take when this is done:
Update the version in the project.json files to remove the pre-release identifier

Make it possible to give information about response codes/descriptions using attributes

I just saw there is a milestone 0.1 defined, so I'll add some things I know off which are incomplete.

At the moment it's not possible to provide response code/description information using attributes. Since you can only use primitives, so it's not possible to add and array of these tuples to SwaggerRouteAttribute. I'm thinking about adding a SwaggerRouteResponseAttribute which looks like:

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SwaggerRouteResponseAttribute : Attribute
{
    // can be used to describe the Response Model. 
    // This is currently a property of SwaggerRouteAttribute)
    public SwaggerRouteResponseAttribute(Type type) { }

    // can be used to describe a possible response status/description
    public SwaggerRouteResponseAttribute(int code, string description = null) { }

    // ...
}

This would make SwaggerRouteAttribute.Response obsolete.

Nancy.NancyContext not found

I'm referencing the version in NuGet and get:

[HandlerException: Handler for Nancy.NancyContext was not found.]
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context) +263
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +40

[DependencyResolverException: Missing dependency.
Component Nancy.Swagger.Annotations.SwaggerAnnotationsConverter has a dependency on Nancy.NancyContext, which could not be resolved.
Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.]
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +222
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency) +117
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +320
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +25
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context) +237
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +35
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +123
Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226
Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23
Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +281
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency) +117
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +320
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +25
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context) +237
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +35
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.<>c__DisplayClass1.b__0(Action1 afterCreated) +22 Castle.MicroKernel.Lifestyle.Scoped.DefaultLifetimeScope.GetCachedInstance(ComponentModel model, ScopedInstanceActivationCallback createInstance) +47 Castle.MicroKernel.Lifestyle.ScopedLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +103 Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226 Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23 Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12 Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy) +107 Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.ResolveAll(Type service, IDictionary arguments, IReleasePolicy policy) +149 Castle.MicroKernel.DefaultKernel.ResolveAll(Type service) +13 Castle.Windsor.WindsorContainer.ResolveAll() +71 Nancy.Bootstrappers.Windsor.WindsorNancyBootstrapper.GetAllModules(NancyContext context) +116 Nancy.Routing.RouteCache..ctor(INancyModuleCatalog moduleCatalog, INancyContextFactory contextFactory, IRouteSegmentExtractor routeSegmentExtractor, IRouteDescriptionProvider routeDescriptionProvider, ICultureService cultureService, IEnumerable1 routeMetadataProviders) +184

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeConstructorInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +303
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, ConstructorCandidate constructor) +78
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType) +47

[ComponentActivatorException: ComponentActivator: could not instantiate Nancy.Routing.RouteCache]
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType) +296
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, ConstructorCandidate constructor, Object[] arguments) +158
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +49
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +123
Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226
Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23
Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +281
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency) +117
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +320
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +25
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context) +237
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +35
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +123
Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226
Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23
Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +281
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency) +117
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +320
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +25
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context) +237
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +35
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +123
Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226
Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23
Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency) +281
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency) +117
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +320
Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) +25
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context) +237
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context) +35
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context) +21
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden) +16
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally) +40
Castle.MicroKernel.Lifestyle.SingletonLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy) +123
Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden) +226
Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired) +23
Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context) +12
Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy) +107
Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy) +42
Castle.MicroKernel.DefaultKernel.Resolve(Type service, IDictionary arguments) +14
Castle.Windsor.WindsorContainer.Resolve() +63
Nancy.Bootstrappers.Windsor.WindsorNancyBootstrapper.GetEngineInternal() +27
Nancy.Bootstrapper.NancyBootstrapperBase`1.SafeGetNancyEngineInstance() +33

[InvalidOperationException: Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and inspect the innerexception for more details.]
Nancy.Bootstrapper.NancyBootstrapperBase1.SafeGetNancyEngineInstance() +87 Nancy.Bootstrapper.NancyBootstrapperBase1.GetEngine() +24
Nancy.Hosting.Aspnet.NancyHttpRequestHandler..cctor() +35

[TypeInitializationException: The type initializer for 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler' threw an exception.]
Nancy.Hosting.Aspnet.NancyHttpRequestHandler..ctor() +0
Moose.WebAPI.Infrastructure.Windsor.NancyAspHttpRequestHandler..ctor() +29

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +206
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1065
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +124
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +20
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +60
System.Web.Configuration.HandlerFactoryCache..ctor(String type) +46
System.Web.HttpApplication.GetFactory(String type) +86
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +224
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Any ideas? Thanks.

Swagger 2.0

Hi,

I'm using the project and I'd like to help out as I think I want to make it a critical piece for a REST API. Are there any plans for supporting Swagger 2.0? I'm open to helping out on other parts as well.

Adam

JetBrains.Annotations 8.1.11.55

I downloaded those package version :

And as I,m using Ninject I added a binding to SwaggerAnnotationsProvider

I debugged and everything seem to goes fine but on the browser side I'm getting this :

Could not load file or assembly \u0027JetBrains.Annotations, Version=8.1.11.55, Culture=neutral, PublicKeyToken=1010a0d8d6380325\u0027 or one of its dependencies. The located assembly\u0027s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)\r\n at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)\r\n at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)\r\n at System.Reflection.CustomAttribute.GetAttributeUsage(RuntimeType decoratedAttribute)\r\n at System.Reflection.CustomAttribute.AttributeUsageCheck(RuntimeType attributeType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes)\r\n at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)\r\n at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)\r\n at System.Reflection.CustomAttribute.IsDefined(RuntimeType type, RuntimeType caType, Boolean inherit)\r\n at Swagger.ObjectModel.ReflectionExtensions.IsDefined[TAttribute](ICustomAttributeProvider provider, Boolean inherits) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\ReflectionExtensions.cs:line 24\r\n at Swagger.ObjectModel.SwaggerModel.SwaggerSerializerStrategy.GetterValueFactory(Type type) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SwaggerModel.cs:line 101\r\n at Swagger.ObjectModel.Reflection.ReflectionUtils.ThreadSafeDictionary2.AddValue(TKey key) in C:\\projects\\nancy-swagger\\src\\Swagger.ObjectModel\\SimpleJson.cs:line 2018\r\n at Swagger.ObjectModel.Reflection.ReflectionUtils.ThreadSafeDictionary2.Get(TKey key) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SimpleJson.cs:line 2009\r\n at Swagger.ObjectModel.Reflection.ReflectionUtils.ThreadSafeDictionary`2.get_Item(TKey key) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SimpleJson.cs:line 2072\r\n at Swagger.ObjectModel.SwaggerModel.SwaggerSerializerStrategy.TrySerializeUnknownTypes(Object input, Object& output) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SwaggerModel.cs:line 73\r\n at Swagger.ObjectModel.PocoJsonSerializerStrategy.TrySerializeNonPrimitiveObject(Object input, Object& output) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SimpleJson.cs:line 1324\r\n at Swagger.ObjectModel.SimpleJson.SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, Object value, StringBuilder builder) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SimpleJson.cs:line 1041\r\n at Swagger.ObjectModel.SimpleJson.SerializeObject(Object json, IJsonSerializerStrategy jsonSerializerStrategy) in C:\projects\nancy-swagger\src\Swagger.ObjectModel\SimpleJson.cs:line 607\r\n at Swagger.ObjectModel.SwaggerModel.ToJson()

Xml Comments

@yahehe, @jnallard,

what do you guys think about extending Nancy.Swagger with ability to auto discover models (request/response) and/or using descriptions from XML documentation (summary... etc)?

Thanks

How to describe models

I have a couple of routes that return non-primitive types. I know how to include them in the swagger specification, but how do I influence the types and documentation of the properties on those models. E.g. a DateTime property is always exposed in the Swagger spec as a string.

Support standalone generation of swagger.json

This is not an issue, more of a question of understanding:

From the examples, it seems like the intended use of this library is at runtime of the Nancy application. That is, annotations or metadata modules are used to produce a .../swagger.json path on the web server where the Swagger definitions can be accessed.

Is there any support for generating this file in a standalone project? For my use case, I would very much prefer the "simple" approach of adding a new C# project referencing my Nancy project, analyze its annotations, and write the output to a file (which I can then publish/use/... separately).
(I would use this e.g. on CI to generate the swagger.json for manual inspection)

If this is not yet possible, and there is some interest in it, I would be happy to provide a PR.

Thinking about the swagger-ui

Hi guys,

After I use this project for some months , I have a questions here:

Why not includes the static resources of the swagger-ui ?

I find out that the demos use Response.AsRedirect($"http://petstore.swagger.io/?url=http://localhost:{port}/api-docs") to work. It's also a good way ! But sometimes it's vary slow when I open this url .Cost lots of time to wait!!

So I want to ask if there are somethings other you are considering for this?

And here is my point :

Including the static resources and add a new route which returns a html page (the document) will make our project run and debug more easier and spend less time to wait the response of the website.

For my own solution, I always include the static resource when creating a new project, and make them as the Embedded resource , and it can make me spend less time to wait the response.

The module code:

Get("/swagger-ui",_=>
{
    var url = $"{Request.Url.BasePath}/api-docs";
    return View["doc", url];
 });

The javascript code:

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
      url: "@Model",
    dom_id: '#swagger-ui',
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

  window.ui = ui
}

And it works fine for me.
image

Alternative ISwaggerMetadataConverter implementation

I'm thinking about implementing an ISwaggerMetadataConverter which provides the SwaggerRouteData by discovering it using some attributes and reflection. Something like the way it can be done using Swagger in Apache CXF (https://github.com/wordnik/swagger-core/wiki/Java-CXF-Quickstart)

I'm aware this is less abstract/generic than using the metadata provided by NancyFx, but I'm one of those guys who likes the documentation a bit 'closer' to the actual code ;-)

Is such an implementation something which you might like in this repository/package? If so, I will create a PR, else I will put it in its own package.

Setup Issue

Hi guys,

Great project. However I've spent all weekend trying to make it work as expected.

If I add SwaggerRoute attributes to the methods the output in /api-docs/[Module] changes but if I try to make use of the [Module]MetadataModule method I just get the default output.

I've uploaded a very basic demo project I created for reference here:

https://github.com/cloudified/NancySwaggerTest.git

The ultimate issue I'm trying to fight is when using swagger-codegen I'm getting the following:

ValidationError(resourceListing,apiVersion is required,ERROR)
ValidationError(apiDeclaration,apiVersion is required,ERROR)
ValidationError(apiDeclaration,basePath is required,ERROR)

and I'm guessing the way I add those attributes is to use MetadataModule

All help appreciated,
-- Danny

XXXModule naming convention is required

A 'Module' suffix on the NancyModule class is required when it should be ambivalent. So, public class XXXModule : NancyModule {} works, whereas public class XXXController : NancyModule {} does not.

For example, changing HomeModule to HomeController in Nancy.Swagger.Demo and then accessing http://localhost:1234/api-docs, I get:

{"swaggerVersion":"1.2","apis":[]}

versus the correct response of:

{"swaggerVersion":"1.2","apis":[{"path":"/users"}]}

Remove Dependency on AWSSDK

The Base Cimpress.Nancy project should not require AWS, but we have it currently to allow loading the config from S3.
This should either be removed (and left for the consumer of this library to implement themselves) or perhaps a new project called Cimpress.Nancy.AWS can be created (which adds extra classes and helpers for working with AWS and Nancy).

Dictionaries are not serializing correctly to Json

Dictionaries are not serializing correctly to Json. You can see this in the "models" in https://github.com/khellang/Nancy.Swagger/blob/master/test/Nancy.Swagger.Annotations.Tests/SwaggerAnnotationsConverterTests.Get_TestModulePath_ReturnsApiDeclaration.approved.txt

I'm not sure how to solve this. I tried some things in the SwaggerSerializerStrategy but could not come up with a generic solution.

The following test reproduces the bug:

[Fact]
public void ToJson_ModelWithSingleProperty_ReturnsJsonString()
{
    new Model
    {
        Id = "some-model",
        Properties = new Dictionary<string, ModelProperty>()
        {
            { "some-type", new ModelProperty { Type = "some-type" } }
        }
    }.ToJson().ShouldEqual("{\"id\":\"some-model\",\"properties\":[{\"some-type\":{\"type\":\"some-type\"}}]}");
}

Any thoughts?

Is self host supported?

Hi, I'm trying to get Nancy.Swagger working in a self-hosted environment.
I'm using Nancy 1.4.3 so I switched on the right branch and tried the sample.
All run fine if hosted in IIS but fails if Nancy is self hosted.
It seems that MetadataModules aren't loaded and I get this output:

  "paths": {
    "/users": {
      "get": {
        "summary": "Warning: no annotated method found for this route",
        "description": "[example]",
        "operationId": "GetUsers"
      },
      "parameters": []
    }

Is this a known issue?
Thanks, Marco

Ideas about parts of spec which are not implemented yet

Is there any metadata in Nancy available we could use for authorizations and produces, consumes? For example, might we use the registered ResponseProcessors to determine produces?

I was just wondering if you guys have any ideas about this already.

Problem installing nuget package

Install-Package : Could not install package 'Swagger.ObjectModel 2.1.0-alpha'. You are trying to install this package into a project that targets '.NETFramework,Version=vx.x', but the packag
e does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:1

  • Install-Package Swagger.ObjectModel -Pre
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

I tried changing target framework a few times but without success. Any ideas? :)

Nancy.Swagger up for adoption!

Cross-posted from NancyFx/Nancy#1486 (comment):

OK, I think it's time for me to put Nancy.Swagger up for adoption.

Here are my reasons:

I'm not using Nancy much for production (read; work) stuff anymore. Quite frankly, I don't do much server-side web at all ATM, so I've lost some interest ๐Ÿ˜ž

I also lost quite a bit of steam realizing how much frickin' work it takes to get some decent metadata out of Nancy, simply because of its dynamic nature. Everything has to be explicitly declared, hand-holding the framework every step of the way, and I don't see this changing. Not very SDHP! ๐Ÿ˜œ

And finally; time is a scarse, invaluable resource, and there are tons of things to do. Based on the above, I've concluded that spending huge amounts of my time on Nancy.Swagger is not really what I want. It's not fair to anyone that the project just sits there because I don't have interest or cycles to spend on it.

So... If someone would like to keep working on it, or simply scrap it altogether and use the name for a new project, just shout out, and I'll transfer the repository and NuGet package owner rights. ๐Ÿ˜„

Thanks! ๐Ÿ‘ฏ

Non-Primitive IEnumerables Not Modeled Correctly

Attempting to model a class such as this:

public class SubClass1 
{
    public string item1 {get; set;}
    public string item2 {get; set;}
}
public class MainClass 
{
    public string name {get; set;}
    public IList<SubClass1> Items {get; set;}
}

Results in an empty array of type "unknown" (null), like this:

{
  "name": "string",
  "Items": [
    null
  ]
}

After reading through the code, I believe the problem is in GetModelsForRoutes() (DefaultSwaggerMetadataConverter.cs). I changed it from this:

protected IEnumerable<SwaggerModelData> GetModelsForRoutes(
            IList<SwaggerRouteData> routeData,
            IList<SwaggerModelData> modelData)
        {
            return routeData.GetDistinctModelTypes().Select(type => EnsureModelData(type, modelData));
        }

to this:

protected IEnumerable<SwaggerModelData> GetModelsForRoutes(
            IList<SwaggerRouteData> routeData,
            IList<SwaggerModelData> modelData)
        {
            foreach (Type distictModel in routeData.GetDistinctModelTypes())
            {
                foreach (Type t in distictModel.GetProperties().Select(property => property.PropertyType.GetGenericArguments().FirstOrDefault()).Where(t => t != null && !Primitive.IsPrimitive(t)))
                {
                    yield return EnsureModelData(t, modelData);
                }
                yield return EnsureModelData(distictModel, modelData);
            }
        }

and it works as intended

{
  "name": "string",
  "Items": [
    {
       "item1": "string",
       "item2": "string"
    }
  ]
}

Fix versioning to be dynamic

Right now the package versioning is hardcoded.
Fix this to be dynamic so we don't need to update the value every time we want to deploy to nuget

Creating meta data with ApiPath or ResourcePath using the DSL does nothing

If you have ApiPath/ResourcePath together or individually when the swagger-ui is run you don't see the meta data for the root route

@liddellj is aware of this as I showed him in Jabbr

    Describe["Home"] = description => description.AsSwagger(with =>
            {
                with.ApiPath("/");
                with.ResourcePath("/");
                with.Summary("The root of the API");
                with.Notes("This is the root of the API when no other segments are passed");
                with.PathParam<string>("name", "a person's name");
            });

What to do before a (pre)release to NuGet

I think we cover the required parts of the spec at the moment. There are some things we don't support yet (for example authorizations , File datatype) but I think the software already is pretty usefull.

Are we at a point we can start thinking about pushing a pre-release?

For me personally, it would lower the bar to actually start experimenting with it in develop/production environments, which hopefully leads to finding the issues quicker.

If so, what steps need to be taken to get there?

Guidence on usage

Hi All

I was excited to find this project today, looking for a way to make my nancy http api self documenting.

I have no clue how to use it? The only config I see in the example is a single static folder convention that is mapping a folder that doesn't exist in the project? What am I missing?

Abstracting JSON

I noticed you explicitly removed the usage of JSON.NET. I'd like to add support back in via an interface. Would this be useful? Is there an interface that already exists? I haven't stared too hard at the abstractions so I'm unsure if I just need to implement an already existing interface.

Namespace issues when discovering Metadata/Swagger information

I was having some issues when putting this into a project I'm working on. After some head scratching I worked out that the Metadata/Swagger info is not getting discovered if the namespaces of the module being described are different.

To reproduce run this https://github.com/jchannon/swaggerbug/tree/master/WebApplication2

Visit http://localhost:11959/content/swagger-ui/index.html to see swagger then see the comments here about how to get the Metadata/Swagger info to appear https://github.com/jchannon/swaggerbug/blob/master/WebApplication2/HomeModule.cs#L29

UPDATE : I think its to do with Nancy.MetadataModule conventions but can't see where to override them ๐Ÿ˜Ÿ

Problem with demo project

I'm attempting to run the demo project. If I run it (in Chrome) I see the following page at localhost:port/api-docs, rather than the Swagger UI:

{
swaggerVersion: "1.2",
  apis: [
  {
    path: "/users"
  }
]
}

Is there another URL I should be using?

Also note I had to add the following to Web.config to get the bootstrapper to run:

<nancyFx>
    <bootstrapper assembly="Nancy.Swagger.Demo" type="Nancy.Swagger.Demo.Bootstrapper" />
</nancyFx>

Validation failed

@yahehe, @jnallard,

Found few strange things. swagger.json produced by Nancy.Swagger is invalid.
This is validator i used http://bigstickcarpet.com/swagger-parser/www/index.html

{  
   "swagger":"2.0",
   "info":{  
      "title":"some api",
      "description":"Our awesome api service",
      "contact":{  
         "name":"Bla",
         "email":"[email protected]"
      },
      "version":"0.0.1"
   },
   "paths":{  
      "/api/v1/data":{  
         "post":{  
            "tags":[  
               "some tag"
            ],
            "summary":"summary",
            "description":"description",
            "operationId":"id",
            "parameters":[  
               {  
                  "name":"Data",
                  "in":"formData",
                  "description":"Object containing data",
                  "type":"Data"
               }
            ],
            "responses":{  
               "DataResponse":{  
                  "schema":{  
                     "$ref":"#/definitions/DataResponse"
                  }
               }
            },
            "security":{ 
                     "apiKey" :[]
            }
         },
         "parameters":[  

         ]
      }
   },
   "definitions":{  
      "Data":{  
         "properties":{  
            "password":{  
               "type":"string"
            },
            "username":{  
               "type":"string"
            }
         },
         "type":"object",
         "$ref":"#/definitions/Data"
      },
      "DataResponse":{  
         "properties":{  
            "expiry":{  
               "type":"integer"
            },
            "token":{  
               "type":"string"
            }
         },
         "required":[  
            "expiry"
         ],
         "type":"object",
         "$ref":"#/definitions/DataResponse"
      }
   },
   "securityDefinitions":{  
      "Bearer":{  
         "type":"apiKey",
         "description":"Authentication with Bearer token",
         "name":"Authorization",
         "in":"header"
      }
   },
   "tags":[  
      {  
         "name":"some tag"
      }
   ]
}

There are some points:

  • security should be array of objects where object key is auth type and its value - array of strings
  • response keys should be status codes only
  • IN key in parameters should be 'body' not 'formData'
  • in same parameter type is not allowed, but schema should be present

What do you think about this?

Thanks.

Ignoring parameters in documentation

A Nancy route that operates async is defined like this:

Get("/", async (args, ct) => await GetSomethingAsync(args, ct));

Not including args didn't seem to work for me. Anyway...

When using Nancy.Swagger.Annotations the args and ct above show up in the swagger documentation even if they are unused and show up as undocumented. The cancellation token in particular is kind of annoying and clutters things up because it's not actually part of a webapi call, it's a cancellation token used by Nancy to cancel an operation during a disconnection, etc. As far as I could tell it's impossible to set a parameter to ignore. To demonstrate what I mean, if the definition of GetSomethingAsync was defined as:

private SomethingObject GetSomethingAsync(
                  [RouteParam(ParameterIn.IgnoreInDocumentation)] dynamic args,
                  [RouteParam(ParameterIn.IgnoreInDocumentation)] CancellationToken cancel)
{
  return new SomthingObject();
} 

That would be cool. Is there a work around for this issue?

Poor/No documentation for v1.4

I'm attempting to use Nancy.Swagger Version 2.1.1 with Nancy v1.4.3. There really isn't any documentation for this version so I have having trouble getting this set up, specifically, what should the Nancy bootstrapper look like to get this going. When I navigate to localhost:80/api-docs I get an error:

"Message":"Something went horribly, horribly wrong while servicing your request.","Details":"Nancy.RequestExecutionException: Oh noes! ---> Swagger.ObjectModel.Builders.RequiredFieldException: 'Paths' is required.\r\n   at Swagger.ObjectModel.Builders.SwaggerRootBuilder.Build()

No idea what I'm doing wrong. If anyone has some example code that would be great.

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.