Write a basic api in .net core that allows CRUD operations for rental locations
- User
Write a basic api in .net core that allows CRUD operations for rental locations
- Assistant
Certainly! Below is a step-by-step guide to creating a basic ASP.NET Core Web API that allows CRUD (Create, Read, Update, Delete) operations for rental locations. This example uses Entity Framework Core with an in-memory database for simplicity.
Prerequisites
- .NET 6 SDK or later installed on your machine.
- An IDE or code editor like Visual Studio, Visual Studio Code, or JetBrains Rider.
Step 1: Create a New ASP.NET Core Web API Project
Open your terminal or command prompt, navigate to the directory where you want to create the project, and run:
dotnet new webapi -n RentalLocationsApiThis command creates a new ASP.NET Core Web API project named
RentalLocationsApi.Step 2: Add the RentalLocation Model
Navigate to the project directory:
cd RentalLocationsApiCreate a new
Modelsfolder and add aRentalLocationclass.File structure:
RentalLocationsApi/ ├── Controllers/ ├── Models/ │ └── RentalLocation.cs ├── Program.cs ├── RentalLocationsApi.csprojRentalLocation.cs
namespace RentalLocationsApi.Models { public class RentalLocation { public int Id { get; set; } // Primary Key public string Name { get; set; } // Name of the rental location public string Address { get; set; } // Address public string City { get; set; } // City public string State { get; set; } // State or Province public string PostalCode { get; set; } // Postal Code public string Country { get; set; } // Country } }Step 3: Set Up the RentalLocationContext
Create a
Datafolder and add aRentalLocationContextclass to handle database operations using Entity Framework Core.File structure:
RentalLocationsApi/ ├── Controllers/ ├── Data/ │ └── RentalLocationContext.cs ├── Models/ │ └── RentalLocation.cs ├── Program.cs ├── RentalLocationsApi.csprojRentalLocationContext.cs
using Microsoft.EntityFrameworkCore; using RentalLocationsApi.Models; namespace RentalLocationsApi.Data { public class RentalLocationContext : DbContext { public RentalLocationContext(DbContextOptions<RentalLocationContext> options) : base(options) { } public DbSet<RentalLocation> RentalLocations { get; set; } } }Step 4: Configure Services in Program.cs
Modify
Program.csto add the database context to the service container.Program.cs
using Microsoft.EntityFrameworkCore; using RentalLocationsApi.Data; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Configure Entity Framework Core to use an in-memory database builder.Services.AddDbContext<RentalLocationContext>(options => options.UseInMemoryDatabase("RentalLocationsDb")); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Seed the database with initial data using (var scope = app.Services.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<RentalLocationContext>(); SeedData(context); } void SeedData(RentalLocationContext context) { if (!context.RentalLocations.Any()) { context.RentalLocations.AddRange( new RentalLocation { Name = "Downtown Branch", Address = "123 Main St", City = "Metropolis", State = "NY", PostalCode = "10001", Country = "USA" }, new RentalLocation { Name = "Uptown Branch", Address = "456 Elm St", City = "Metropolis", State = "NY", PostalCode = "10002", Country = "USA" } ); context.SaveChanges(); } } // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();Step 5: Create the RentalLocationsController
Add a new controller named
RentalLocationsControllerin theControllersfolder.File structure:
RentalLocationsApi/ ├── Controllers/ │ └── RentalLocationsController.cs ├── Data/ │ └── RentalLocationContext.cs ├── Models/ │ └── RentalLocation.cs ├── Program.cs ├── RentalLocationsApi.csprojRentalLocationsController.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using RentalLocationsApi.Data; using RentalLocationsApi.Models; namespace RentalLocationsApi.Controllers { [Route("api/[controller]")] [ApiController] public class RentalLocationsController : ControllerBase { private readonly RentalLocationContext _context; public RentalLocationsController(RentalLocationContext context) { _context = context; } // GET: api/RentalLocations [HttpGet] public async Task<ActionResult<IEnumerable<RentalLocation>>> GetRentalLocations() { return await _context.RentalLocations.ToListAsync(); } // GET: api/RentalLocations/5 [HttpGet("{id}")] public async Task<ActionResult<RentalLocation>> GetRentalLocation(int id) { var rentalLocation = await _context.RentalLocations.FindAsync(id); if (rentalLocation == null) { return NotFound(); } return rentalLocation; } // POST: api/RentalLocations [HttpPost] public async Task<ActionResult<RentalLocation>> PostRentalLocation(RentalLocation rentalLocation) { _context.RentalLocations.Add(rentalLocation); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetRentalLocation), new { id = rentalLocation.Id }, rentalLocation); } // PUT: api/RentalLocations/5 [HttpPut("{id}")] public async Task<IActionResult> PutRentalLocation(int id, RentalLocation rentalLocation) { if (id != rentalLocation.Id) { return BadRequest(); } _context.Entry(rentalLocation).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!RentalLocationExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // DELETE: api/RentalLocations/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteRentalLocation(int id) { var rentalLocation = await _context.RentalLocations.FindAsync(id); if (rentalLocation == null) { return NotFound(); } _context.RentalLocations.Remove(rentalLocation); await _context.SaveChangesAsync(); return NoContent(); } private bool RentalLocationExists(int id) { return _context.RentalLocations.Any(e => e.Id == id); } } }Step 6: Test the API
Run the application:
dotnet runBy default, the API will be hosted at
https://localhost:5001orhttp://localhost:5000.Using Swagger UI
ASP.NET Core includes Swagger support by default in development mode. You can use Swagger UI to test the API endpoints by navigating to
https://localhost:5001/swaggerin your browser.Testing Endpoints
Get all rental locations
GET https://localhost:5001/api/RentalLocationsGet a rental location by ID
GET https://localhost:5001/api/RentalLocations/1Create a new rental location
POST https://localhost:5001/api/RentalLocations Content-Type: application/json { "name": "Midtown Branch", "address": "789 Oak St", "city": "Metropolis", "state": "NY", "postalCode": "10003", "country": "USA" }Update an existing rental location
PUT https://localhost:5001/api/RentalLocations/1 Content-Type: application/json { "id": 1, "name": "Downtown Branch Updated", "address": "123 Main St", "city": "Metropolis", "state": "NY", "postalCode": "10001", "country": "USA" }Delete a rental location
DELETE https://localhost:5001/api/RentalLocations/1Conclusion
You've now created a basic ASP.NET Core Web API that supports CRUD operations for rental locations. This can serve as a foundation for building more complex applications, integrating authentication, or connecting to a persistent database like SQL Server or SQLite.
Note: This example uses an in-memory database, which is suitable for development and testing purposes. For a production application, you should use a persistent database. You can change the
UseInMemoryDatabasecall inProgram.csto use another database provider supported by Entity Framework Core.Feel free to ask if you have any questions or need further assistance!