Build a .NET API in 3 minutes with Chat GPT 🤯
Tags: dotnet, csharp, chatgpt, openai
Published: 2023-03-29 09:00:00

Do you know that you can create a REST API in C# in less than 3 minutes? Look no further! Read on to discover the secrets of rapid .NET API development with Chat-GPT. Let’s dive in!

## Creating Rest API in C# #

Chat-GPT input: **Create a REST API in C# to manage a workout routine**

> Sure, here’s a basic example of how to create a REST API in C# using the ASP.NET Core framework to manage a workout routine:
> 
> 1.  First, create a new ASP.NET Core Web Application project in Visual Studio.
> 2.  Add the required NuGet packages for your project: Microsoft.AspNetCore.Mvc.NewtonsoftJson and Microsoft.EntityFrameworkCore.SqlServer.
> 3.  Create a new database to store workout routine data.
> 4.  Create a new model class for the workout routine with properties like name, description, duration, etc.
> 5.  Create a new DbContext class to interact with the database.
> 6.  Create a new controller class with methods to handle CRUD operations for the workout routine, such as GET, POST, PUT, and DELETE requests.
> 7.  Use attribute routing to specify the endpoints for each method in the controller.
> 8.  Use dependency injection to inject the DbContext into the controller.
> 9.  Use the JsonResult method to return the workout routine data in JSON format.
> 10.  Test the API using a tool like Postman.
> 
> Here’s some sample code to get you started:
> 
> ```csharp
> // WorkoutRoutine model class
> public class WorkoutRoutine
> {
>     public int Id { get; set; }
>     public string Name { get; set; }
>     public string Description { get; set; }
>     public int Duration { get; set; }
> }
> 
> // WorkoutRoutineDbContext class
> public class WorkoutRoutineDbContext : DbContext
> {
>     public WorkoutRoutineDbContext(DbContextOptions<WorkoutRoutineDbContext> options) : base(options)
>     {
>     }
> 
>     public DbSet<WorkoutRoutine> WorkoutRoutines { get; set; }
> }
> 
> // WorkoutRoutineController class
> [Route("api/[controller]")]
> [ApiController]
> public class WorkoutRoutineController : ControllerBase
> {
>     private readonly WorkoutRoutineDbContext _context;
> 
>     public WorkoutRoutineController(WorkoutRoutineDbContext context)
>     {
>         _context = context;
>     }
> 
>     [HttpGet]
>     public IActionResult Get()
>     {
>         var workoutRoutines = _context.WorkoutRoutines.ToList();
>         return new JsonResult(workoutRoutines);
>     }
> 
>     [HttpGet("{id}")]
>     public IActionResult Get(int id)
>     {
>         var workoutRoutine = _context.WorkoutRoutines.FirstOrDefault(w => w.Id == id);
>         if (workoutRoutine == null)
>         {
>             return NotFound();
>         }
>         return new JsonResult(workoutRoutine);
>     }
> 
>     [HttpPost]
>     public IActionResult Post(WorkoutRoutine workoutRoutine)
>     {
>         _context.WorkoutRoutines.Add(workoutRoutine);
>         _context.SaveChanges();
>         return new JsonResult(workoutRoutine);
>     }
> 
>     [HttpPut("{id}")]
>     public IActionResult Put(int id, WorkoutRoutine workoutRoutine)
>     {
>         var existingWorkoutRoutine = _context.WorkoutRoutines.FirstOrDefault(w => w.Id == id);
>         if (existingWorkoutRoutine == null)
>         {
>             return NotFound();
>         }
>         existingWorkoutRoutine.Name = workoutRoutine.Name;
>         existingWorkoutRoutine.Description = workoutRoutine.Description;
>         existingWorkoutRoutine.Duration = workoutRoutine.Duration;
>         _context.SaveChanges();
>         return new JsonResult(existingWorkoutRoutine);
>     }
> 
>     [HttpDelete("{id}")]
>     public IActionResult Delete(int id)
>     {
>         var workoutRoutine = _context.WorkoutRoutines.FirstOrDefault(w => w.Id == id);
>         if (workoutRoutine == null)
>         {
>             return NotFound();
>         }
>         _context.WorkoutRoutines.Remove(workoutRoutine);
>         _context.SaveChanges();
>         return new JsonResult(workoutRoutine);
>     }
> }
> ```
> 
> Note: This is just a basic example to get you started. You may need to modify the code to fit your specific requirements. Additionally, it’s important to add authentication and authorization to your API to ensure that only authorized users can access and modify the workout routine data

---

## Adding properties

Chat-GPT input: **Please add the following properties to the workout class from the previous example: Name, Series, Repetitions, and an enumeration of days of the week**

> Sure, here’s an updated version of the WorkoutRoutine class with the new properties and enum:
> 
> ```csharp
> // WorkoutRoutine model class
> public class WorkoutRoutine
> {
>     public int Id { get; set; }
>     public string Name { get; set; }
>     public int Series { get; set; }
>     public int Repetitions { get; set; }
>     public DayOfWeek DayOfWeek { get; set; }
>     public string Description { get; set; }
>     public int Duration { get; set; }
> }
> 
> // DayOfWeek enum
> public enum DayOfWeek
> {
>     Monday,
>     Tuesday,
>     Wednesday,
>     Thursday,
>     Friday,
>     Saturday,
>     Sunday
> }
> ```
> 
> You can use these properties in the controller methods to create, read, update, and delete workout routines. For example, to create a new workout routine, you would send a POST request to the API with a JSON object containing the workout routine data, like this:
> 
> ```json
> {
>     "name": "Push-ups",
>     "series": 3,
>     "repetitions": 10,
>     "dayOfWeek": "Monday",
>     "description": "Do push-ups with good form.",
>     "duration": 10
> }
> ```
> 
> And the corresponding controller method to handle this request would look like this:
> 
> ```csharp
> [HttpPost]
> public IActionResult Post(WorkoutRoutine workoutRoutine)
> {
>     _context.WorkoutRoutines.Add(workoutRoutine);
>     _context.SaveChanges();
>     return new JsonResult(workoutRoutine);
> }
> ```
> 
> Similarly, you can use the other properties and enum values in the other controller methods to retrieve, update, and delete workout routines as needed.

---

## Adding database schema

Chat-GPT input: **Please add the database schema for the WorkoutRoutineDbContext from the previous example.**

> Sure, here’s an updated version of the WorkoutRoutineDbContext class with the database schema for the WorkoutRoutine entity:
> 
> ```csharp
> // WorkoutRoutineDbContext class
> public class WorkoutRoutineDbContext : DbContext
> {
>     public WorkoutRoutineDbContext(DbContextOptions<WorkoutRoutineDbContext> options) : base(options)
>     {
>     }
> 
>     public DbSet<WorkoutRoutine> WorkoutRoutines { get; set; }
> 
>     protected override void OnModelCreating(ModelBuilder modelBuilder)
>     {
>         modelBuilder.Entity<WorkoutRoutine>(entity =>
>         {
>             entity.ToTable("WorkoutRoutines");
> 
>             entity.HasKey(e => e.Id);
> 
>             entity.Property(e => e.Name)
>                 .IsRequired()
>                 .HasMaxLength(50);
> 
>             entity.Property(e => e.Series)
>                 .IsRequired();
> 
>             entity.Property(e => e.Repetitions)
>                 .IsRequired();
> 
>             entity.Property(e => e.DayOfWeek)
>                 .IsRequired();
> 
>             entity.Property(e => e.Description)
>                 .HasMaxLength(100);
> 
>             entity.Property(e => e.Duration)
>                 .IsRequired();
>         });
>     }
> }
> ```
> 
> This code creates a table named “WorkoutRoutines” with columns for each property in the WorkoutRoutine class. The Id property is set as the primary key for the table, and the other properties are set as required with appropriate maximum lengths. The OnModelCreating method is used to configure the database schema for the WorkoutRoutine entity. You can update the schema as needed to fit your specific requirements.

---

## Calling the API

Chat-GPT input: **Now show me an example of how I can call this API and create a new workout with the name chest, 4 series with 12 repetitions on Mondays and Thursdays from a nodejs app**

> Sure, here’s an example of how to call the API and create a new workout routine using Node.js and the axios library:
> 
> ```javascript
> const axios = require('axios');
> 
> const createWorkout = async () => {
>   try {
>     const newWorkout = {
>       name: 'Chest',
>       series: 4,
>       repetitions: 12,
>       dayOfWeek: 'Monday',
>       description: 'Chest workout routine',
>       duration: 60
>     };
>     const res = await axios.post('http://localhost:5000/api/workoutroutine', newWorkout);
>     console.log(res.data);
>   } catch (error) {
>     console.error(error);
>   }
> };
> 
> createWorkout();
> ```
> 
> This code defines a new workout routine object with the specified properties and uses the axios library to send a POST request to the API endpoint at “[http://localhost:5000/api/workoutroutine](http://localhost:5000/api/workoutroutine)” with the new workout routine object as the request body. The response data is then logged to the console. You can modify this code to fit your specific requirements and run it in a Node.js environment to create new workout routines via the API.

And that’s it! We already have our .NET API created in less than 3 minutes with Chat-GPT. Amazing, isn’t it?