Stop Unexpected Redirects Before They Become API Errors

Your API request comes back with 200 OK. Unfortunately, the body is a login page. The JSON decoder is unimpressed.

Or the request returns 403, even though you supplied the expected credentials. The response you see may be the end of a redirect, rather than the response to the URL you meant to call.

For an API whose endpoints should answer directly, we can make that contract explicit: do not follow redirects, and check the HTTP status before decoding. This keeps an unexpected 307 visible instead of turning it into a less useful failure somewhere else.

This is an established capability, not a new networking framework. The useful part is attaching it to the request you actually send and proving that the next destination was never contacted.

Decide whether this endpoint should redirect

A Stack Overflow question about a request that worked in Postman but returned 403 on iOS already has an accepted answer: the server redirected /friends to /friends/, and the final request was unauthenticated. Calling the canonical endpoint was one suggested fix.

Start there. If your API expects a trailing slash, include it. If it moved, update the configured endpoint. Reattaching credentials to every redirected request is a much larger decision than correcting a URL.

Rejecting every redirect is appropriate when your API contract requires a direct response. It is intentionally unsuitable for a URL shortener, a download that legitimately moves to a CDN, or an authentication flow that depends on redirects. Those need their own explicit policy.

Our real-transport testing article checks cookies and what happens when redirects are followed. Here we’ll implement its deferred policy boundary: rejecting the redirect and checking that nothing reached its destination.

Give this task a redirect delegate

Put these blocks together in your networking target. The async Foundation API used here is available from iOS 15 and macOS 12. The examples use current Swift syntax and were checked with Xcode 27.2 and Swift 6.4.2, including projects that default to MainActor isolation.

The delegate has no mutable state. Its only decision is to decline the proposed request:

import Foundation

nonisolated final class RejectRedirects: NSObject, URLSessionTaskDelegate {
    func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        willPerformHTTPRedirection response: HTTPURLResponse,
        newRequest request: URLRequest,
        completionHandler: @escaping @Sendable (URLRequest?) -> Void
    ) {
        completionHandler(nil)
    }
}

According to Apple’s delegate contract, passing nil declines the redirect and returns the redirect response’s body. It does not turn the redirect into a thrown transport error. We still need to examine the response.

That callback runs for default and ephemeral sessions. Background sessions follow redirects automatically, so the helper below rejects a background session before creating the task.

The nonisolated declaration keeps this stateless delegate independent of a project’s default actor. It isn’t a request to move work to a particular thread.

Keep HTTP failures separate from decoding

Pass the delegate to data(for:delegate:). Defining a delegate class without attaching an instance changes nothing about the request.

nonisolated enum APIRequestError: Error, Equatable {
    case backgroundSessionUnsupported
    case nonHTTPResponse
    case unexpectedRedirect(status: Int)
    case httpStatus(Int)
}

nonisolated func loadAPIData(
    for request: URLRequest,
    using session: URLSession
) async throws -> Data {
    guard session.configuration.identifier == nil else {
        throw APIRequestError.backgroundSessionUnsupported
    }

    let (data, response) = try await session.data(
        for: request,
        delegate: RejectRedirects()
    )

    guard let http = response as? HTTPURLResponse else {
        throw APIRequestError.nonHTTPResponse
    }

    switch http.statusCode {
    case 200..<300:
        return data
    case 301, 302, 303, 307, 308:
        throw APIRequestError.unexpectedRedirect(status: http.statusCode)
    default:
        throw APIRequestError.httpStatus(http.statusCode)
    }
}

nonisolated struct AccountSummary: Decodable, Sendable {
    let unreadCount: Int
}

nonisolated func fetchAccountSummary(
    from endpoint: URL,
    using session: URLSession
) async throws -> AccountSummary {
    var request = URLRequest(url: endpoint)
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    let data = try await loadAPIData(for: request, using: session)
    return try JSONDecoder().decode(AccountSummary.self, from: data)
}

Use your app’s canonical HTTPS endpoint and its existing, appropriately configured default or ephemeral session. Reuse that session across requests; this helper neither creates nor invalidates it. Add your app’s authentication through its existing mechanism. The example does not implement login, token refresh, or credential forwarding.

There are now three useful failure categories:

ResultWhat the caller receives
An unexpected 302 or 307APIRequestError.unexpectedRedirect, before decoding
A direct 401, 403, or 500APIRequestError.httpStatus
Successful HTTP with malformed JSONThe decoder’s error

Transport failures and cancellation propagate from URLSession; there is no catch-all that replaces them with “bad JSON.” The helper accepts other 2xx responses too. If this particular endpoint requires exactly 200, tighten that contract; 204 has no summary for the decoder to read.

Because this uses data(for:), the response body is collected in memory, including a rejected redirect’s body. Use it for small API responses. Declining redirection is not a response-size limit or a streaming implementation.

The policy belongs to this task. Another request using the same session can still follow redirects if it does not install this delegate. If your session already implements redirect handling, deliberately choose which policy should own these requests rather than assuming both handlers will combine.

Prove that the destination received nothing

A test that feeds a canned 302 to your response parser only tests the parser. It does not establish that Foundation called your delegate before making another request.

Donny Wals’s discussion of network mocking separates testing a client abstraction from testing through URLSession. Keep those fast tests. For this particular contract, add real local HTTP traffic, as also recommended in Apple DTS’s reply in the Swift Forums discussion.

The runnable sample includes the exact code above, a Python 3 fixture, and a small iOS test app. The runner starts two servers bound only to 127.0.0.1, on independently assigned ports. One issues redirects; the other records arrivals. No external service or real credentials are involved.

Each case uses a unique identifier in its URLs. Both servers record arrivals under that identifier. After the rejecting request completes, the test reads the combined record and checks that it contains the original request but no destination request. The ordinary-follow control checks that the same fixture really can deliver a redirect.

Run python3 verify.py from the extracted sample for macOS checks and iOS-target compilation. Run python3 verify.py --ios for native Simulator checks; the README documents the selected simulator and requirements. The test app’s local-networking setting is for this HTTP fixture, not an instruction to weaken your production transport settings.

The important comparisons are:

CaseRequired observation
Redirect with the rejecting delegateOriginal redirect status; zero destination arrivals
Same route without the delegateDestination receives the request, proving the fixture can redirect
Relative redirect on the same originRejected too; this policy is not a host allowlist
Cross-port 307 carrying a small POSTRejected before its method, marker header, or body reaches the destination
Ordinary and rejecting tasks on one sessionEach request keeps its own behavior

The fixture covers 301, 302, 303, 307, and 308, direct success and HTTP failure, malformed successful JSON, and transport/cancellation paths. Tests run against actual Foundation on macOS and iOS 27.2 Simulator in both isolation modes. Compilation targets iOS 15; that is not a claim of runtime testing on iOS 15 or a physical device.

When a test fails, the server’s recorded requests are the evidence. Seeing the right error locally is only half the promise; seeing no unintended request at the destination is the other half.