Introduction

Web APIs are an important part of modern application development. A web application, mobile application, or another service can use an API to communicate with a backend application and exchange data.

When working with ASP.NET Core, developers commonly use Web APIs to build CRUD applications, integrate external services, connect mobile applications, expose business functionality, and communicate between different services.

I have put together this list of frequently asked Web API questions with simple explanations and practical C# examples. The goal is not only to understand the definitions but also to see how these concepts are used when building an API.

The examples in this article use common scenarios such as customers, products, authentication, pagination, and API security.

1. What Is an API?

API stands for Application Programming Interface.

An API provides a defined way for one software application to communicate with another application or service.

For example, an application might communicate with a payment provider through its API. Similarly, a mobile application can communicate with a backend API to retrieve customer or product information.

A simplified flow looks like this:

Client Application
       |
       | HTTP Request
       v
     Web API
       |
       | Business Logic
       v
    Database
       |
       | Response
       v
Client Application

2. What Is a Web API?

A Web API is an API that communicates over web protocols, most commonly HTTP or HTTPS.

For example:

GET /api/customers

The client sends a request to the API, and the server can return customer information, commonly represented as JSON.

[
    {
        "id": 1,
        "name": "John"
    }
]

ASP.NET Core provides built-in support for creating Web APIs.

3. What Is REST API?

REST stands for Representational State Transfer.

REST is an architectural style commonly used for designing HTTP APIs. RESTful APIs typically use HTTP methods and resource-oriented URLs.

For example:

GET    /api/products
GET    /api/products/5
POST   /api/products
PUT    /api/products/5
PATCH  /api/products/5
DELETE /api/products/5

REST APIs are generally stateless, meaning the server does not rely on previous requests to understand the current request.

4. What Is the Difference Between Web API and REST API?

Web API and REST API are related but are not exactly the same thing.

Web API

REST API

General term for an API exposed over web technologies

API designed according to REST principles

Can use different architectural approaches

Follows REST constraints

Commonly uses HTTP/HTTPS

Uses HTTP/HTTPS

Can return JSON, XML, or other representations

JSON is commonly used, but REST is not limited to JSON

ASP.NET Core can be used to build Web APIs

ASP.NET Core can also be used to build RESTful APIs

Therefore, REST describes an architectural approach, while Web API is a broader term.

5. What Are HTTP Methods?

HTTP methods indicate what the client wants to do with a resource.

Method

Common Usage

GET

Retrieve data

POST

Create a resource

PUT

Replace or update a resource

PATCH

Partially update a resource

DELETE

Delete a resource

For example:

GET /api/customers
POST /api/customers
PUT /api/customers/10
PATCH /api/customers/10
DELETE /api/customers/10

The exact behavior should be defined by the API's contract.

6. What Is the Structure of an ASP.NET Core Web API Project?

A typical project can be organized like this:

Controllers/
Models/
DTOs/
Services/
Repositories/
Data/
Middleware/
Program.cs
appsettings.json

Each folder can have a specific responsibility.

The exact structure can vary depending on the application's architecture.

7. What Is an API Controller?

A controller contains endpoint methods that handle HTTP requests.

For example:

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetCustomers()
    {
        return Ok();
    }
}

[ApiController] enables API-specific behavior, while [Route] defines the route template.

8. How Do You Connect a Web API to SQL Server?

ASP.NET Core applications can connect to SQL Server using technologies such as Entity Framework Core or ADO.NET.

Using Entity Framework Core, a connection string can be stored in configuration:

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DATABASE;Trusted_Connection=True;TrustServerCertificate=True;"
    }
}

The connection can then be configured in the application.

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString(
            "DefaultConnection")));

For direct database access, ADO.NET can also be used:

using SqlConnection connection =
    new SqlConnection(connectionString);

await connection.OpenAsync();

9. What Is JSON and Why Is It Used by APIs?

JSON stands for JavaScript Object Notation.

It is a text-based format commonly used to exchange structured data between applications.

Example:

{
    "id": 1,
    "name": "John",
    "email": "[email protected]"
}

JSON is widely supported by programming languages and client applications, which makes it convenient for HTTP APIs.

10. What Are HTTP Status Codes?

HTTP status codes tell the client how the server handled a request.

Some commonly used status codes are:

Status Code

Meaning

200

Request succeeded

201

Resource created

204

Request succeeded with no response body

400

Bad request

401

Authentication is required or failed

403

Request is understood but access is forbidden

404

Resource not found

500

Unexpected server error

For example:

return NotFound();

returns an HTTP 404 response.

11. What Is the Difference Between Authentication and Authorization?

Authentication answers:

Who are you?

Authorization answers:

What are you allowed to do?

For example, a user may successfully authenticate but still not have permission to access an administrator endpoint.

Authentication and authorization are separate concepts and are commonly implemented using mechanisms such as cookies, JWT bearer authentication, OAuth 2.0, and OpenID Connect.

12. What Is a JWT?

JWT stands for JSON Web Token.

A JWT can be used to carry claims about an authenticated user between a client and an API.

A common flow is:

Login
  |
  v
Authentication API
  |
  v
JWT Token
  |
  v
Client
  |
  | Authorization: Bearer <token>
  v
Protected API

An ASP.NET Core API can configure JWT bearer authentication and protect endpoints using:

[Authorize]
[HttpGet]
public IActionResult GetProfile()
{
    return Ok();
}

JWTs should be configured and validated carefully, including issuer, audience, signing key, expiration, and algorithm requirements.

13. What Is API Versioning?

API versioning allows an application to support different API contracts over time.

For example:

/api/v1/products
/api/v2/products

Versioning can be useful when changing an API would otherwise break existing clients.

The exact versioning approach depends on the API design and the ASP.NET Core libraries being used.

14. What Is Swagger?

Swagger is commonly used to describe and interact with APIs through an OpenAPI document and user interface.

A Swagger UI can provide information such as:

It is particularly useful during API development and testing.

15. What Is CORS?

CORS stands for Cross-Origin Resource Sharing.

Browsers enforce same-origin restrictions. CORS allows a server to specify which cross-origin browser requests are permitted.

For example:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
    {
        policy.WithOrigins("https://example.com")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

The policy must then be added to the middleware pipeline.

Avoid using unrestricted CORS such as AllowAnyOrigin() in production unless the application's security requirements explicitly allow it.

16. What Is SOAP API?

SOAP stands for Simple Object Access Protocol.

SOAP is a protocol that commonly uses XML messages and formal service contracts. It is still used in some enterprise and legacy integration scenarios.

SOAP and REST are different approaches. The choice depends on the integration requirements, existing systems, contracts, tooling, and security requirements.

17. What Is the Difference Between REST and SOAP?

REST

SOAP

Architectural style

Protocol

Commonly uses HTTP

Can operate over different underlying transports

JSON is commonly used

XML is commonly used

Generally simpler to consume

Often has more formal contracts and standards

Common in web and mobile APIs

Common in many enterprise and legacy integrations

It is better to choose between them based on the application's requirements rather than assuming one approach is always better.

18. What Is GraphQL?

GraphQL is a query language and runtime for APIs that allows clients to request the fields they need.

For example:

{
    user(id: 5) {
        name
        email
    }
}

Instead of defining many REST endpoints for different response shapes, a GraphQL API can allow the client to specify the required fields.

19. What Is gRPC?

gRPC is a high-performance RPC framework commonly used for service-to-service communication.

It uses Protocol Buffers for defining service contracts and messages.

A simplified service definition looks like:

service CustomerService {
    rpc GetCustomer (CustomerRequest)
        returns (CustomerResponse);
}

gRPC can be useful for internal service communication where strongly typed contracts and efficient communication are important.

20. What Is a WebSocket?

WebSocket provides a persistent connection that supports communication in both directions between a client and server.

It can be useful for scenarios such as:

Unlike a typical request-response API call, the server can send data to a connected client when an event occurs.

21. What Is SignalR?

ASP.NET Core SignalR is a library for adding real-time functionality to applications.

It abstracts much of the connection management and can use WebSockets when available, with other supported transports when necessary.

A common use case is sending a notification from the server to connected clients.

For example, a server can send a message through a SignalR hub:

await hubContext.Clients.All
    .SendAsync("ReceiveMessage", "New order received");

22. What Are API Routes?

Routes determine which URL maps to a controller or endpoint.

For example:

/api/customers
/api/customers/5

A controller can define a route using:

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
}

The HTTP method attributes then define individual operations.

23. What Is the Difference Between PUT and PATCH?

PUT and PATCH have different semantics.

PUT is generally used when the client sends a complete replacement representation of a resource.

PATCH is used for partial modifications.

For example:

PUT /api/customers/5

can represent replacing the customer representation.

A PATCH request might change only the email:

PATCH /api/customers/5

The exact implementation depends on the API contract.

24. What Is an API Gateway?

An API gateway can act as an entry point between clients and multiple backend services.

A simplified architecture is:

Client
  |
  v
API Gateway
  |
  +---- Customer Service
  |
  +---- Order Service
  |
  +---- Payment Service

Depending on the gateway, it can provide capabilities such as routing, authentication integration, rate limiting, and request transformation.

25. What Is Rate Limiting?

Rate limiting controls how many requests a client can make during a specific period.

For example, an API could restrict a client to a certain number of requests during a defined time window.

Rate limiting can help protect APIs from excessive traffic and resource exhaustion.

ASP.NET Core provides rate-limiting capabilities that can be configured according to the application's requirements.

26. What Is an API Key?

An API key is a value supplied by a client to identify or authenticate access to an API.

For example:

GET /api/products?key=YOUR_API_KEY

However, placing sensitive API keys in URLs is generally undesirable because URLs can appear in logs, browser history, and other locations.

Where supported, credentials should be sent using an appropriate request header or authentication mechanism.

27. What Is Postman?

Postman is a tool commonly used for developing and testing APIs.

It can be used to:

For example, a POST request can contain:

{
    "name": "John",
    "email": "[email protected]"
}

28. How Do You Secure a Web API?

API security requires multiple layers.

Common practices include:

Security should be designed according to the application's threat model and requirements.

29. What Is a DTO?

DTO stands for Data Transfer Object.

A DTO defines the data that an API accepts or returns instead of exposing an internal entity directly.

For example:

public class CustomerDto
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}

A DTO can prevent internal database fields from accidentally becoming part of the public API contract.

30. What Is the Repository Pattern?

The Repository Pattern separates data-access operations from business logic.

For example:

public interface ICustomerRepository
{
    Task<Customer?> GetByIdAsync(int id);
    Task<List<Customer>> GetAllAsync();
}

A service can depend on the interface instead of directly containing database-query code.

The pattern can be useful in some architectures, although it is not mandatory for every ASP.NET Core application. Entity Framework Core already provides data-access abstractions through DbContext and DbSet.

31. What Is Middleware?

Middleware is software that participates in processing HTTP requests and responses.

A middleware component can perform work before and after the next component in the pipeline.

Common uses include:

A simplified middleware pipeline looks like:

Request
   |
   v
Middleware
   |
   v
Middleware
   |
   v
Controller/Endpoint
   |
   v
Response

32. What Is API Pagination?

Pagination limits how many records an API returns in a single response.

For example:

GET /api/products?page=1&pageSize=10

A paginated response might look like:

{
    "page": 1,
    "pageSize": 10,
    "totalCount": 100,
    "items": [
        {
            "id": 1,
            "name": "Product 1"
        }
    ]
}

Pagination can reduce response size and avoid retrieving large numbers of records unnecessarily.

For database-backed APIs, pagination should generally be applied at the database query level rather than retrieving the entire table first.

33. What Is HATEOAS?

HATEOAS stands for Hypermedia as the Engine of Application State.

It is a REST constraint where responses can contain links that describe available actions.

For example:

{
    "id": 1,
    "name": "Book",
    "_links": {
        "self": "/products/1",
        "update": "/products/1"
    }
}

HATEOAS is part of the broader REST architecture, but many APIs do not implement it fully.

34. What Is OpenAPI Specification?

OpenAPI is a standard for describing HTTP APIs in a machine-readable format.

An OpenAPI document can describe:

Tools can use the specification to generate documentation, client code, testing interfaces, and other development resources.

35. What Is Idempotency in APIs?

An operation is idempotent when making the same request multiple times has the same intended effect as making it once.

For example, GET is designed to be idempotent when used according to HTTP semantics.

PUT and DELETE also have idempotent semantics, although the actual server implementation still needs to follow those semantics correctly.

POST is generally not idempotent.

For operations such as payment processing where duplicate requests can be dangerous, an API may implement an idempotency key mechanism.

36. What Is a Callback URL?

A callback URL is an endpoint that another system calls to deliver information asynchronously.

For example:

Application
    |
    | Request
    v
External Service
    |
    | Later calls callback
    v
Callback URL

The exact implementation depends on the external service.

The application should authenticate and validate incoming callback requests rather than trusting the request simply because it came to a known URL.

37. What Is a Webhook?

A webhook is a mechanism where one system sends an HTTP request to another system when an event occurs.

For example:

Payment Completed
       |
       v
Payment Provider
       |
       | HTTP POST
       v
Your Webhook Endpoint

A webhook endpoint should validate the request and, where supported, verify the provider's signature before processing the event.

38. What Is a REST Client?

A REST client is an application or component that sends HTTP requests to a REST API.

A REST client could be:

In .NET, HttpClient is commonly used to call HTTP APIs.

using HttpClient client = new HttpClient();

var response =
    await client.GetAsync("https://example.com/api/products");

var content =
    await response.Content.ReadAsStringAsync();

39. What Is API Testing?

API testing verifies that an API behaves according to its expected contract.

Common tests include:

For example, a test can verify that requesting a missing customer returns HTTP 404 instead of HTTP 200.

40. What Is the Difference Between MVC Controller and API Controller?

In ASP.NET Core, both can be implemented using controller classes, but they commonly serve different purposes.

MVC Controller

API Controller

Commonly handles web UI requests

Handles API requests

Can return views

Commonly returns data

Used with Razor views

Commonly used for HTTP APIs

Can use Controller

Commonly uses ControllerBase

Designed for web UI scenarios

Designed for API scenarios

For example:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

An API controller can be:

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok();
    }
}

41. How Do You Create a Web API CRUD Project?

A typical CRUD API provides endpoints for creating, reading, updating, and deleting resources.

For a customer resource:

GET    /api/customers
GET    /api/customers/5
POST   /api/customers
PUT    /api/customers/5
DELETE /api/customers/5

A typical controller might contain:

[HttpGet]
public IActionResult GetCustomers()
{
    return Ok();
}

[HttpGet("{id}")]
public IActionResult GetCustomer(int id)
{
    return Ok();
}

[HttpPost]
public IActionResult AddCustomer(CustomerDto model)
{
    return Created();
}

[HttpPut("{id}")]
public IActionResult UpdateCustomer(
    int id,
    CustomerDto model)
{
    return NoContent();
}

[HttpDelete("{id}")]
public IActionResult DeleteCustomer(int id)
{
    return NoContent();
}

42. How Do You Create a POST Web API Endpoint?

A POST endpoint can receive data from the client and create a new resource.

[HttpPost]
public IActionResult AddCustomer(CustomerDto model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    // Save customer

    return Ok(new
    {
        message = "Customer saved successfully."
    });
}

In a production API, the method should also perform the required business validation and persistence operations.

43. How Do You Call a Web API from JavaScript?

The browser's fetch() API can be used to make HTTP requests.

fetch("/api/customers")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });

For production applications, the client should also check the HTTP status and handle network and API errors appropriately.

44. How Do You Display API Data in an HTML Table?

After receiving JSON data, JavaScript can create table rows dynamically.

fetch("/api/customers")
    .then(response => response.json())
    .then(data => {
        let rows = "";

        data.forEach(customer => {
            rows += `
                <tr>
                    <td>${customer.id}</td>
                    <td>${customer.name}</td>
                </tr>`;
        });

        document.querySelector("#customerTable tbody")
            .innerHTML = rows;
    });

When inserting API data into HTML, developers should ensure that untrusted data is handled safely to avoid introducing cross-site scripting vulnerabilities.

45. What Types of Projects Use Web APIs?

Web APIs are commonly used in many types of applications, including:

The API provides a communication layer between clients and backend functionality.

Practical Web API Request Flow

The concepts discussed above can be combined into a typical application flow.

For example, when a user opens a customer management application:

Browser / Mobile App
        |
        | GET /api/customers
        v
ASP.NET Core API
        |
        v
Authentication / Authorization
        |
        v
Controller
        |
        v
Service
        |
        v
Repository / DbContext
        |
        v
SQL Server
        |
        v
JSON Response
        |
        v
Browser / Mobile App

This separation allows each part of the application to have a clear responsibility.

Common Web API Mistakes

While building Web APIs, some common mistakes should be avoided.

Returning Everything from the Database

Avoid loading an entire database table when the client needs only a small subset of records. Use filtering, projection, sorting, and pagination where appropriate.

Exposing Database Entities Directly

Using DTOs can provide better control over the public API contract.

Ignoring HTTP Status Codes

Returning HTTP 200 for every situation makes it harder for clients to understand whether an operation succeeded or failed.

Allowing Unrestricted CORS

CORS should be configured according to the application's actual frontend origins and security requirements.

Storing Secrets in Source Code

Database passwords, API keys, JWT signing secrets, and SMTP credentials should not be committed to source control.

Missing Authorization Checks

Authentication confirms the user's identity, but authorization determines what that user can access.

Best Practices for ASP.NET Core Web APIs

The following practices can help when designing and maintaining APIs:

  1. Use clear and consistent resource-oriented routes.

  2. Return appropriate HTTP status codes.

  3. Validate incoming data.

  4. Use DTOs for public request and response contracts.

  5. Implement authentication and authorization where required.

  6. Use HTTPS.

  7. Protect secrets using appropriate configuration and secret-management mechanisms.

  8. Apply pagination to large datasets.

  9. Add structured logging and centralized exception handling.

  10. Document the API using OpenAPI.

  11. Test both successful and failure scenarios.

  12. Apply rate limiting where appropriate.

  13. Keep API contracts backward compatible when possible.

  14. Avoid exposing unnecessary database or internal implementation details.

Conclusion

Web APIs are a fundamental part of modern application development, and understanding the concepts behind them is more useful than simply memorizing definitions.

In this article, we covered 45 common Web API questions, including REST, HTTP methods, controllers, SQL Server connectivity, authentication, JWT, CORS, Swagger, GraphQL, gRPC, WebSockets, SignalR, DTOs, middleware, pagination, webhooks, API testing, and CRUD operations.

The most important lesson is that building a good Web API involves more than creating controller endpoints. API design also requires appropriate HTTP semantics, validation, security, error handling, data-access practices, documentation, and maintainability.

If you are learning ASP.NET Core Web API, a good next step is to build a small CRUD project and apply these concepts one at a time. This gives you practical experience with the complete flow from the client request to the API, business logic, database, and final response.