Creating a REST API in C# step by step with example

Samim.Hossain
Samim Hossain
Published on Nov, 05 2024 2 min read 0 comments
image

Creating a REST API in C# involves several steps, from setting up your development environment to coding, testing, and deploying your API. Here’s a detailed guide to get you started:

Step 1: Set Up Your Development Environment

  1. Install .NET SDK: Make sure you have the .NET SDK installed. You can download it from the Microsoft .NET website.
  2. Choose an IDE: Visual Studio or Visual Studio Code are popular choices for C# development. Install one of these if you haven’t already.

Step 2: Create a New Project

  1. Open Visual Studio: Select "Create a new project".
  2. Select Project Template: Choose "ASP.NET Core Web API" and click "Next".
  3. Configure the Project: Provide a project name, location, and solution name. Click "Create".
  4. Select Framework: Choose the appropriate .NET version (e.g., .NET 5.0) and click "Create".

Step 3: Define Your API

  1. Define Models: Create classes that represent the data structure.
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

   2. Create a Database Context: Define a context class that interacts with the database using Entity Framework.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Product> Products { get; set; }
}

   3. Configure Services: Add the database context in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddControllers();
}

Step 4: Implement Controllers

  1. Create Controllers: Implement controllers to handle HTTP requests.
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _context;

    public ProductsController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        return await _context.Products.ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> GetProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);

        if (product == null)
        {
            return NotFound();
        }

        return product;
    }

    [HttpPost]
    public async Task<ActionResult<Product>> PostProduct(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> PutProduct(int id, Product product)
    {
        if (id != product.Id)
        {
            return BadRequest();
        }

        _context.Entry(product).State = EntityState.Modified;
        await _context.SaveChangesAsync();

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteProduct(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        _context.Products.Remove(product);
        await _context.SaveChangesAsync();

        return NoContent();
    }
}

Step 5: Run and Test Your API

  1. Run Your API: Press F5 in Visual Studio to run your API.
  2. Test Using Postman or Browser: Use Postman or a browser to test your endpoints.
    • GET: https://localhost:5001/api/products
    • POST: https://localhost:5001/api/products (with JSON body)
    • PUT: https://localhost:5001/api/products/{id}
    • DELETE: https://localhost:5001/api/products/{id}

Step 6: Deploy Your API

  1. Choose a Hosting Service: Options include Azure, AWS, or any cloud service that supports .NET applications.
  2. Configure for Production: Ensure your appsettings.json is configured correctly for your production database.
  3. Deploy: Use Visual Studio's Publish tool to deploy your API to the chosen hosting service.

This process should get you up and running with a basic REST API in C#.

0 Comments