Lessons in this course (10)

7. API test automation

Intermediate★ Must knowLesson 7 of 10
csharp
public class OrdersApiTests
{
    private readonly HttpClient _client = new() { BaseAddress = new Uri("https://api.example.com") };

    [Test]
    public async Task Create_order_returns_201_and_location()
    {
        _client.DefaultRequestHeaders.Authorization = new("Bearer", await TokenHelper.GetAsync());
        var response = await _client.PostAsJsonAsync("/api/orders", new { customerId = 42, lines = new[] { new { productId = 1, qty = 2 } } });

        Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));
        Assert.That(response.Headers.Location, Is.Not.Null);
        var order = await response.Content.ReadFromJsonAsync<OrderDto>();
        Assert.That(order!.Lines, Has.Count.EqualTo(1));
    }

    [Test]
    public async Task Missing_token_returns_401()
        => Assert.That((await new HttpClient().GetAsync("https://api.example.com/api/orders")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
}

What to check: status codes, response body and schema, headers, error messages (ProblemDetails), auth (401/403), validation (400), idempotency, pagination, performance thresholds. For ASP.NET Core apps, WebApplicationFactory<Program> runs the API in-memory for fast integration tests; WireMock.Net fakes third-party APIs.

Postman: collections, environments, pre-request scripts, pm.test(...) assertions, run in CI with Newman.