Generate .NET Client from Swagger

Antoine Griffard picture Antoine Griffard · Jan 8, 2019 · Viewed 23k times · Source

What tool can I use to generate a .NET Client to consume from a Swagger definition?

For example, I started trying NSwag Studio and I would like to be able to generate the code to look like the Repository classes I am used to create.

Note to the voters wishing to delete the question: the answers and comments of the question are useful for readers, so deletion is not a good idea. As SO doesn’t allow questions seeking recommendations for books, tools, software libraries, the question should stay closed or (even better) consider to migrate to http://softwarerecs.stackexchange.com

Answer

stringy05 picture stringy05 · Jan 16, 2019

You can use the swagger-codegen tool from the swagger project. It produces C# files that use

  • RestClient for the HTTP calls
  • Newtonsoft.Json for json marshalling
  • .NET DataContract for the models.

You can either download the cli app or use the online editor. The petstore example models look like this:

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace IO.Swagger.Model {

    /// <summary>
    /// 
    /// </summary>
    [DataContract]
    public class Order {
      /// <summary>
      /// Gets or Sets Id
      /// </summary>
      [DataMember(Name="id", EmitDefaultValue=false)]
      [JsonProperty(PropertyName = "id")]
      public long? Id { get; set; }

      /// <summary>
      /// Gets or Sets PetId
      /// </summary>
      [DataMember(Name="petId", EmitDefaultValue=false)]
      [JsonProperty(PropertyName = "petId")]
      public long? PetId { get; set; }
 .... snip ....
}