En está ocasión veremos cómo crear un proyecto backend con C#.
Debemos tener instalado Dotnet. En caso de no tenerlo, lo puedes descargar desde este sitio: https://dotnet.microsoft.com/en-us/download
Abrimos una terminal y tecleamos:
$ dotnet new webapi -n proyecto-backend $ cd proyecto-backend
Esto nos creará un proyecto llamado ``proyecto-backend``. La estructura será similar a esto:
proyecto-backend/ appsettings.Development.json appsettings.json bin/ obj/ Program.cs Properties/ proyecto-backend.csproj proyecto-backend.http proyecto-backend.sln
Veamos el programa principal. El cual se trata de una API de descripciones climáticas.
Program.cs
var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; app.MapGet("/weatherforecast", () => { var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now.AddDays(index)), Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast; }) .WithName("GetWeatherForecast") .WithOpenApi(); app.Run(); record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); }
Ahora echemoslo a andar:
$ dotnet build $ dotnet run
Abrimos el navegador en la ruta: http://localhost:5071/weatherforecast
Nos mostrará un JSON:
[ { "date": "2025-10-06", "temperatureC": 7, "summary": "Freezing", "temperatureF": 44 }, { "date": "2025-10-07", "temperatureC": -3, "summary": "Hot", "temperatureF": 27 }, { "date": "2025-10-08", "temperatureC": 11, "summary": "Freezing", "temperatureF": 51 }, { "date": "2025-10-09", "temperatureC": 29, "summary": "Warm", "temperatureF": 84 }, { "date": "2025-10-10", "temperatureC": -5, "summary": "Mild", "temperatureF": 24 } ]
Ahora creemos otra sencilla API con C#.
Creando una sencilla API con C#
Crearemos un servicio sencillo que nos permita generar un JSON con la siguiente estructura:
[ { "animal": "gato", "raza:":"felino", "nombre":"Don Panther", "id": 1 }, { "animal": "gato", "raza:":"felino", "nombre":"El Guererais", "id": 2 }, { "animal": "gato", "raza:":"felino", "nombre":"Caramelo", "id": 3 } ]
Crearemos una capeta ``model`` donde tendremos dos clases:
- Felino.cs
- Gato.cs (que hereda de Felino.cs)
Felino.cs
using System; namespace model { public class Felino { private long id; private string nombre; private string raza; public void comer() { Console.WriteLine("El felino come"); } public long Id { get; set; } public string Nombre { get; set; } public string Raza { get; set; } } }
Gato.cs
using System; namespace model { public class Gato : Felino { public Gato(long id, string nombre, string raza) { this.Id = id; this.Nombre = nombre; this.Raza = raza; } public void comer() { Console.WriteLine("El gato come"); } } }
Ahora el programa principal lucirá así:
Program.cs
using model; var builder = WebApplication.CreateBuilder(args); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); var gatos = new List<Gato> { new Gato(1, "Don Panther", "felino"), new Gato(2, "El Guererais", "felino"), new Gato(3, "Caramelo", "felino") }; app.MapGet("/gatos", () => { var resultado = gatos.Select(g => new { raza = g.Raza, nombre = g.Nombre, id = g.Id }); return Results.Json(resultado); }) .WithName("GetGatos") .WithOpenApi(); app.Run();
Construyamos y ejecutemos la aplicación:
$ dotnet build $ dotnet run
Abrimos el navegador en la ruta: http://localhost:5071/gatos
Nos mostrará nuestro JSON:
[ { "raza": "felino", "nombre": "Don Panther", "id": 1 }, { "raza": "felino", "nombre": "El Guererais", "id": 2 }, { "raza": "felino", "nombre": "Caramelo", "id": 3 } ]
Si queremos ver la página de Swagger de nuestra aplicación abrimos la siguiente URL: http://localhost:5071/swagger/index.html
¡Hemos creado una sencilla API con C#!
Continuaremos con este tema en próximas entregas
Enlaces:
https://dotnet.microsoft.com/
No hay comentarios:
Publicar un comentario