Coder Social home page Coder Social logo

nancy.metadata.openapi's Introduction

Nancy.Metadata.OpenApi Mit License

This library extends Nancy modules in order to produce a specification file that will follow the OpenAPI spec.

You can find the latest specifications of OpenAPI here

This library targets Nancy 2.0, for previous versions that target Nancy 1.X check release that target version 0.7.0 and below.

Note: Since Nancyfx is no longer being maintained i will be deprioritizing this library, please read here for details

Builds

Appveyor Branch Coverage
Build status master CodeCov
Build status develop CodeCov

Packages

NuGet (Stable) MyGet (Prerelease)
NuGet MyGet

Installation

Via nuget:

PM> Install-Package Nancy.Metadata.OpenApi

You also need the Metadata library provided by Nancyfx:

PM> Install-Package Nancy.Metadata.Modules

Usage

Define a docs module that will serve our OpenApi Json (currently only json is supported) document:

using Nancy.Metadata.OpenApi.Model;
using Nancy.Metadata.OpenApi.Modules;

public class DocsModule : OpenApiDocsModuleBase //We must inherit from the OpenApiDocsModuleBase
{
    //Could be an array of Servers corresponding to different environments. 
    public static Server Server
        => new Server() { Description = "My Descripton", Url = "http://localhost:5000/" };

    public static string[] Tags => new string[] { "sample", "openapi" };

    public DocsModule(IRouteCacheProvider routeCacheProvider) :
        base(routeCacheProvider,
        "/api/docs/openapi.json",       //Document location path
        "My API ",                      //Api Title 
        "v1.0",                         //Version of the Api
        Server,
        "/api",                         //Base url
        Tags)                           //Document Tags
    {
    }
}

We could optionally, if the information is needed, add Contact, License and External Docs information:

public class DocsModule : OpenApiDocsModuleBase //We must inherit from the OpenApiDocsModuleBase
{
    public static Server Server
        => new Server() { Description = "My Descripton", Url = "http://localhost:5001/" };

    public static string[] Tags => new string[] { "sample", "openapi" };

    public DocsModule(IRouteCacheProvider routeCacheProvider) :
        base(routeCacheProvider, "/api/docs/openapi.json", "My API 2", "v1.1", Server, "/api", Tags)
    {
        //Optional information.
        WithContact("Contact Information", "[email protected]", "https://jaxelr.github.io");

        //Optional information.
        WithLicense("MIT", "https://opensource.org/licenses/MIT");

        //Optional Information.
        WithExternalDocument("This is a tutorial or a spec doc.", "https://jaxelr.github.io")
    }
}

Then, define the Nancy modules as you would usually do:

//Example using Nancy v2
public class MyModule : NancyModule
{
    public MyModule() : base("/api")
    {
        Get("/hello", r => HelloWorld(), name: "SimpleRequest");
        Get("/hello/{name}", r => Hello(r.name), name: "SimpleRequestWithParameter");
    }
}

//Skipped method implementations for brevity sake...

Finally, you must define the metadata of the operations. To do so, simply declare the metadata module (using Nancy.Metadata.Modules) on the same namespace as the endpoint operations were defined, using the inherited MetadataModule class and the OpenApiRouteMetadata class defined on Nancy.Metadata.OpenApi.Core.

using Nancy.Metadata.Modules;
using Nancy.Metadata.OpenApi.Core;
using Nancy.Metadata.OpenApi.Fluent;

public class MyMetadataModule : MetadataModule<OpenApiRouteMetadata>
{
    public MyMetadataModule()
    {
        Describe["SimpleRequest"] = desc => new OpenApiRouteMetadata(desc)
            .With(i => i.WithResponseModel("200", typeof(SimpleResponseModel), "Sample response")
                        .WithSummary("Simple GET example"));

        Describe["SimpleRequestWithParameter"] = desc => new OpenApiRouteMetadata(desc)
            .With(i => i.WithResponseModel("200", typeof(SimpleResponseModel), "Sample response")
                        .WithRequestParameter("name")
                        .WithSummary("Simple GET with parameters"));
    }
}

Thats pretty much it, the docs endpoint defined above would generate some valid OpenApi Json. You can validate the Open Api endpoint using swagger-ui. (For those unaware, OpenApi used to be called Swagger, so any reference to Swagger usually means version <= 2.0) Check the Compatibility table of UI for usage.

For a working example, see the sample app that uses the Swagger-UI site as a validator.

Contributing

Check the guidelines for a simple explanation on how you could contribute.

nancy.metadata.openapi's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar gzoug avatar jaxelr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nancy.metadata.openapi's Issues

Bug generating methods with body

Type of Issue

[ X ] Bug.
[ ] Feature.

Expected Behavior

The request body must map to the requestBody property of the Path info object.

Actual Behavior

In scenarios of a request with a post body, the object is not mapping correctly to the definition established by OAS.

Steps to Reproduce the Problem

  1. Any request with post and body

Runtime exception when using multiple WithBearerAuthentication

Hello,

Describe the bug

In my MetadataModule implementation I have declared several OpenApiRouteMetadata that, each, have a WithBearerAuthentication description. At runtime I get the error

System.ArgumentException: 'Can not add property bearer to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.'

This occur in the CustomCollectionJsonConverter.cs file at line 26.

Steps to reproduce

Using the following example MetadataModule allows to highlight the issue

public class RootMetadataModule : MetadataModule<OpenApiRouteMetadata>
{
	public RootMetadataModule()
	{

		Describe["ListAvailableProcesses"] = desc => new OpenApiRouteMetadata(desc)
			.With(i => i.WithResponseModel("200", typeof(ProcessesContainer), "List available processes")
						.WithSummary("a description"));

		Describe["SendProcessingRequest"] = desc => new OpenApiRouteMetadata(desc)
			.With(info => info.WithResponseModel("200", typeof(ProcessingResponse), "Request was accepted ")
				.WithResponse("400", "Bad request")
				.WithSummary("POST example")
				.WithRequestModel(typeof(ProcessingRequest), contentType: "application/json", description: "Send processing request")
				.WithBearerAuthentication("JWT", "Please enter the following security token «bla bla»")
				);

		Describe["QueryProcessingState"] = desc => new OpenApiRouteMetadata(desc)
			.With(info => info.WithResponseModel("200", typeof(ProcessingStateResponse), "Request was accepted and processing state is sent back")
				.WithResponse("400", "Bad request")
				.WithSummary("POST example with ProcessingStateRequest model")
				.WithRequestModel(typeof(ProcessingStateRequest), contentType: "application/json", description: "Send processing state request", required: true)
				.WithBearerAuthentication("JWT")
				);

	}
}

Expected behavior

No exception should occur

Proposed Fix

At line 26 in CustomCollectionJsonConverter.cs, if I add the following code, the duplicate key exception is averted; not sure, however, if this does not break something else ...

if (jo.ContainsKey(t.Key))
{
	continue;
}
  • Dotnet version: [dotnet472]
  • Library version: [current GIT version]

I'm using VB.net do I need to do anything differently?

Describe the question

First of all: thank you for your great work on this project. It looks very promising!

I'm evaluating if I can use it in my VB.net project. When I call the endpoint I do get all information but the paths is empty. I've created a simple test project, I've attached the three classes below.

Steps to reproduce (if applicable)

File: PingModule.vb

Imports Nancy

Public Class PingModule
    Inherits NancyModule
    
    Public Sub New 
        MyBase.Get("/ping", Function() "Hello, the time is: " + DateTime.Now, name := "ping")
    End Sub
    
End Class

File: MetaDataModule.vb

Public Class MetaDataModule
    Inherits MetadataModule(Of OpenApiRouteMetadata)

    Public Sub New()
        Describe("ping") = Function(desc) New OpenApiRouteMetadata(desc).With(Function(i) i.WithResponse(HttpStatusCode.OK, "Ping").WithSummary("Ping"))
    End Sub
    
End Class

File: DocsModule.vb

Imports Nancy.Metadata.OpenApi.Model
Imports Nancy.Metadata.OpenApi.Modules
Imports Nancy.Routing

Public Class DocsModule
    Inherits OpenApiDocsModuleBase

    Public Sub New(routeCacheProvider As IRouteCacheProvider)
        MyBase.New(routeCacheProvider, "/api/docs/openapi.json", "Next Rest API ", "v1.0")
    End Sub
    
End Class

The Result is:

{
    "openapi": "3.0.2",
    "info": {
        "version": "v1.0",
        "title": "Ping Test API "
    },
    "servers": [
        {
            "url": "localhost:5000",
            "description": "My Localhost"
        }
    ],
    "paths": {},
    "components": {
        "schemas": {}
    }
}
  • Dotnet version: [ dotnet472]
  • Library version: [0.1.0]

JsonSchema4 was renamed to JsonSchema in NJsonSchema 10.x

Hi Jaxel,
There are some changes in the new 10.x NJsonSchema release.

Describe the bug

Latest NJsonSchema release renamed JsonSchema4 to JsonSchema.

Steps to reproduce

Import NJsonSchema v10.x and try to compile.

Expected behavior

Should compile without warnings.

  • Dotnet version: [dotnet472]
  • Library version: [latest master branch]

Solution

Rename JsonSchema4 to JsonSchema in:

  • OpenApiDocsModuleBase.cs,
  • Component.cs,
  • TypeNameGenerator.cs (also add using NJsonSchema.Generation;),
  • SchemaCache.cs,
  • SchemaGenerator.cs

Thank you !

Best regards,
SoftExpert

Upgrade to NancyFx 2.0 Release Version

Just to keep track of the effort the team at Nancy are going through on their milestone towards 2.0 release.

Once published on nuget we can proceed to upgrade our version.

And also upgrade to netstandard 2.0. Since the next version release will target 2.0.

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.