.NET Core

ASP.NET Core REST API Tutorial: Build a CRUD Backend from Scratch

You need a backend for your Android app. ASP.NET Core 5.0 combined with Entity Framework Core gives you a modern, fast framework for building the API your mobile app will talk to every day. This guide walks you through the complete process: setting up a Web API project, defining your database model, implementing create-read-update-delete operations, and testing everything with Postman. By the end, you'll have a working REST backend you can connect to any client application.

Quick take:

  • The Web API template in Visual Studio provides REST endpoint conventions automatically
  • Entity Framework Core manages database interactions without writing raw SQL queries
  • SQL Server serves as the data store, with connection strings stored safely in appsettings.json
  • Postman lets you test every HTTP method without building a frontend first
  • Separating business logic into services keeps your code maintainable as the project grows

Setting Up Your Project in Visual Studio

Fire up Visual Studio 2019 and select "Create a new project." Choose the ASP.NET Core Web Application template, then pick version 5.0 from the framework dropdown. Select Web API as the project type and hit Create. Visual Studio scaffolds the basic folder structure with Controllers, Models, and Program.cs already in place.

First thing you'll want to do is add the SQL Server provider. Open the NuGet Package Manager and install Microsoft.EntityFrameworkCore.SqlServer. This package lets Entity Framework talk to your database.

Defining Your Data Model

Create a folder named Models in your project directory. Inside it, add a class that represents the data entity you want to work with. For a student management scenario, your class needs properties for the student identifier, roll number, enrollment details, name, branch, and university. Mark the primary key with the appropriate attribute. This model class becomes the blueprint Entity Framework uses to create your database table.

The model should include validation attributes where needed. The Key attribute marks your primary key, and other annotations like Required or StringLength enforce data integrity at the model level.

Creating the Database Context

Entity Framework needs a context class to manage your database operations. This class inherits from DbContext and exposes your models as DbSet properties. When you instantiate your context, you'll pass in options that tell it which database provider to use.

Register your context in the application startup configuration. This registration lets ASP.NET Core's dependency injection system provide your context wherever it's needed. The connection string comes from appsettings.json, keeping your database credentials out of source code.

Building the Service Layer

Your controller shouldn't contain business logic directly. Instead, create a service class that handles all data operations. Define an interface first so you can easily swap implementations later or mock the service during testing.

The interface declares methods for creating new records, retrieving lists of records, updating existing ones, and deleting by identifier. Your service class implements this contract by injecting the database context and performing the actual database work.

This separation makes your code testable and keeps the HTTP handling logic in your controller clean. The controller only handles incoming requests and outgoing responses; the service handles everything else.

Wiring Up the Controller

Add a new controller class that inherits from ControllerBase. Use routing attributes to map HTTP methods to your service calls. The Route attribute defines the URL pattern, and HttpGet, HttpPost, HttpPut, and HttpDelete attributes specify which verb each action handles.

Inject your service through the constructor. ASP.NET Core resolves this dependency automatically when a request comes in. Each action method calls the appropriate service method and returns the result, letting the framework handle serialization.

Testing with Postman

Postman is the quickest way to verify your API works. Set the HTTP method, enter your endpoint URL, and add a JSON body for POST or PUT requests. The tool shows you the server's response immediately, letting you spot errors before writing any client code.

For GET requests, append the record identifier to the URL. For POST, send the complete object as JSON. For PUT, include the identifier in the URL and the updated data in the body. For DELETE, just the identifier in the URL is enough.

Connection String Security

Never hardcode database credentials in your source files. Store the connection string in appsettings.json under the ConnectionStrings section. Use environment variables or Azure Key Vault for production deployments. This practice prevents accidental credential exposure through version control.

Why This Matters

REST APIs built with ASP.NET Core scale well and integrate smoothly with Android apps using Retrofit or Volley. The framework handles routing, model binding, and content negotiation automatically. Entity Framework abstracts the database layer, letting you change providers (SQL Server to PostgreSQL, for example) with minimal code changes.

Say you are building an attendance tracking app for a college. Your Android app sends student check-ins to the API, which stores them in SQL Server. The same API can serve a web dashboard for administrators. One backend powers multiple clients.

Bottom Line

Start with the Web API template to get conventions without configuration. Keep business logic in services, not controllers. Store connection strings safely and test every endpoint with Postman before connecting a client. Once your CRUD operations work, adding authentication or complex queries becomes straightforward.

Key takeaways

  • Use the Web API template to get REST conventions without writing boilerplate
  • Entity Framework Core handles database operations through a typed context class
  • Services separate business logic from HTTP handling, making code testable
  • Store connection strings in appsettings.json, never hardcoded in source files
  • Postman lets you verify every endpoint before connecting a mobile client

Frequently asked questions

Can I use SQLite instead of SQL Server for development?

Yes. Install the SQLite provider package and change the connection string in appsettings.json. SQLite works great for local development and small-scale deployments.

How do I add validation to incoming data?

Use Data Annotations on your model properties like [Required] or [StringLength]. For more complex validation rules, consider FluentValidation as an alternative approach.

Do I need authentication for my API?

Any production API should have authentication. ASP.NET Core supports JWT Bearer tokens, Azure AD, and OAuth providers. Add the authentication middleware in Program.cs and protect controllers with [Authorize] attributes.

What's the difference between PUT and PATCH?

PUT replaces the entire resource with the request body. PATCH applies partial updates to specific fields. For most Android app scenarios, PUT or POST with full objects works fine.

How do I handle errors in the API?

Return appropriate HTTP status codes (404 for not found, 400 for bad request, 500 for server errors). Use try-catch blocks in your service layer and let exceptions bubble up to a global error handler.

Related