= $u_time + 86400) { $modifiedDate = get_the_modified_time('F jS, Y'); echo 'Última modificación: '.$modifiedDate.''; } }?>

Generar JSON Postman Collection desde WebApi

Para aquellos que no conozcan Swagger o que no vean viable su utilización a estas alturas de su proyecto, aquí os dejo el código de un controlador que permite exportar tu WebApi a un JSON que podrás importar en Postman y te permitirá tener todas las operaciones ordenadas en una Colección. Es totalmente configurable, como podréis ver,  y pueden añadirse un sin fin de opciones; aquí solo está hecho lo básico, que os permitirá hacer las llamadas y obtener las respuestas de vuestras operaciones.

Nota: No sirve para .NetCore

[ApiExplorerSettings(IgnoreApi = true)]
[Route("api/postman")]
public class PostmanController : ApiController
{
        [HttpGet]
        public HttpResponseMessage Get()
        {
            var collection = this.Configuration.Properties.GetOrAdd("postmanCollection", this.CreateCollection());

            return this.Request.CreateResponse(HttpStatusCode.OK, collection, "application/json");
        }

        private PostmanCollection CreateCollection()
        {

            var requestUri = this.Request.RequestUri;
            var baseUri = requestUri.Scheme + "://" + requestUri.Host + ":" + requestUri.Port + HttpContext.Current.Request.ApplicationPath;
            var postManCollection = new PostmanCollection
            {
                Id = Guid.NewGuid(),
                Name = "Mi WebAPI",
                Timestamp = DateTime.Now.Ticks,
                Requests = new Collection<PostmanRequest>()
            };
            
            var apiDescriptionsByControllerGroup = this.Configuration.Services.GetApiExplorer().ApiDescriptions.GroupBy(item => item.ActionDescriptor.ControllerDescriptor.ControllerName).ToList();

            var allRequests = new Collection<PostmanRequest>();

            foreach (var apiDescriptionByController in apiDescriptionsByControllerGroup)
            {
                foreach (var action in apiDescriptionByController)
                {
                    var request = new PostmanRequest
                    {
                        CollectionId = postManCollection.Id,
                        Id = Guid.NewGuid(),
                        Method = action.HttpMethod.Method,
                        Url = baseUri.TrimEnd('/') + "/" + action.RelativePath,
                        Description = action.Documentation,
                        Name = action.RelativePath,
                        Data = string.Empty,
                        HeaderData = new List<HeaderData>(),
                        DataMode = "params",
                        Timestamp = 0
                    };

#if DEBUG
                    request.headers = "MyKey1: MyValue1\nMyKey2: MyValue2\n";
                    request.headerData.Add(new HeaderData("MyKey1", "MyValue1"));
                    request.headerData.Add(new HeaderData("MyKey2", "MyValue2"));
#endif
                    allRequests.Add(request);
                }
            }

            postManCollection.Requests = new Collection<PostmanRequest>(allRequests.OrderBy(item => item.Url).ThenBy(item=>item.Method).ToList());
            return postManCollection;

        }
}

Ahora las clases necesarias para  el modelo:

public class PostmanRequest
{
        [JsonProperty(PropertyName = "collectionId")]
        public Guid CollectionId { get; set; }

        [JsonProperty(PropertyName = "data")]
        public string Data { get; set; }

        [JsonProperty(PropertyName = "dataMode")]
        public string DataMode { get; set; }

        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        [JsonProperty(PropertyName = "headers")]
        public string Headers { get; set; }

        [JsonProperty(PropertyName = "id")]
        public Guid Id { get; set; }

        [JsonProperty(PropertyName = "method")]
        public string Method { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "timestamp")]
        public long Timestamp { get; set; }

        [JsonProperty(PropertyName = "url")]
        public string Url { get; set; }

        [JsonProperty(PropertyName = "headerData")]
        public List<HeaderData> HeaderData;
    }

public class HeaderData
{
        public HeaderData(string key, string value)
        {
            this.Key = key;
            this.Value = value;
        }

        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        [JsonProperty(PropertyName = "key")]
        public string Key { get; set; }

        [JsonProperty(PropertyName = "value")]
        public string Value { get; set; }
}

public class PostmanCollection
{
        [JsonProperty(PropertyName = "id")]
        public Guid Id { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "timestamp")]
        public long Timestamp { get; set; }

        [JsonProperty(PropertyName = "requests")]
        public Collection<PostmanRequest> Requests { get; set; }
}

Ahora solo queda ejecutar la WebApi e importar al Postman:

Import Postman Collection

Leave a Reply

Your email address will not be published. Required fields are marked *