NNovaNetworkClientSwift networkingGitHub ↗

Intermediate · 12 min

Declare endpoints with a macro

Generate request construction from a method, a path template, and stored properties.

You’ll buildA typed endpoint whose makeRequest() is generated, executed through the same client pipeline.
1
Step 1

Enable the macro trait

The macro is the only part of the package that needs swift-syntax, so it is opt-in. Leave the trait off and the package resolves no dependencies at all.

Declareendpointswithamacro.swift
dependencies: [
    .package(
        url: "https://github.com/maxches99/NovaNetwork.git",
        from: "2.11.0",
        traits: ["EndpointMacros"]
    )
]
2
Step 2

Supply the base URL once

A shared protocol keeps every operation down to the part that actually differs.

Declareendpointswithamacro.swift
protocol PetstoreAPI: EndpointDefinition {}

extension PetstoreAPI {
    var baseURL: URL {
        URL(string: "https://api.petstore.example.com/v1")!
    }
}
3
Step 3

Declare the operation

petId fills {petId} because the names match. Unmarked properties become query items, and a nil value is omitted rather than sent empty.

Declareendpointswithamacro.swift
@Endpoint(.get, "/pets/{petId}/photos", response: [Photo].self)
struct GetPetPhotos: PetstoreAPI {
    let petId: Int
    var limit: Int?
    @Query("sort_by") var sortBy: String?
    @Header("X-Trace") var trace: String?
}
4
Step 4

Execute it like any endpoint

Generated endpoints run through the same coalescing, caching, retry, middleware, and telemetry pipeline as hand-written ones.

Declareendpointswithamacro.swift
let photos = try await client.execute(
    endpoint: GetPetPhotos(petId: 7, limit: 20),
    authScope: "petstore"
)
✓

Tutorial complete

A typed endpoint whose makeRequest() is generated, executed through the same client pipeline.