GitHub REST API Swift 语言代码

这个 Swift 代码生成器构建于 Swift OpenAPI Generator 之上,并利用了 GitHub REST API 的 OpenAPI 描述。目标是自动化生成 Swift 语言代码,为开发者提供与 GitHub REST API 无缝交互的方式。

用法

例如,您可以导入这些框架来获取 github 用户,或参考 UsersTests.swift

import GitHubRestAPIUsers
import OpenAPIRuntime
import OpenAPIURLSession

let client = Client(serverURL: try Servers.server1(), transport: URLSessionTransport()) 
let users = try await client.users_sol_list().ok.body.json 
完整支持的框架
import GitHubRestAPIActions
import GitHubRestAPIActivity
import GitHubRestAPIApps
import GitHubRestAPIBilling
import GitHubRestAPIChecks
import GitHubRestAPIClassroom
import GitHubRestAPICode_Scanning
import GitHubRestAPICodes_Of_Conduct
import GitHubRestAPICodespaces
import GitHubRestAPICopilot
import GitHubRestAPIDependabot
import GitHubRestAPIDependency_Graph
import GitHubRestAPIDesktop
import GitHubRestAPIEmojis
import GitHubRestAPIGists
import GitHubRestAPIGit
import GitHubRestAPIGitignore
import GitHubRestAPIInteractions
import GitHubRestAPIIssues
import GitHubRestAPILicenses
import GitHubRestAPIMarkdown
import GitHubRestAPIMerge_Queue
import GitHubRestAPIMeta
import GitHubRestAPIMigrations
import GitHubRestAPIOidc
import GitHubRestAPIOrgs
import GitHubRestAPIPackages
import GitHubRestAPIProjects
import GitHubRestAPIPulls
import GitHubRestAPIRate_Limit
import GitHubRestAPIReactions
import GitHubRestAPIRepos
import GitHubRestAPISearch
import GitHubRestAPISecret_Scanning
import GitHubRestAPISecurity_Advisories
import GitHubRestAPITeams
import GitHubRestAPIUsers

教程 展示了以下示例,或参考下方内容。

增强的 issues comment API 代码示例
// Usage.swift
// -
import Foundation
import GitHubRestAPIIssues
import OpenAPIRuntime
import OpenAPIURLSession
import HTTPTypes

struct GitHubRestAPIIssuesExtension {

    let owner: String

    let repo: String

    /// The issue number or pull number.
    let number: Int

    /// Update the comment if the anchor is found; otherwise, create it.
    func comment(anchor: String, body: String) async throws {
        let hidingContent = "<!-- Comment anchor: \(anchor) -->"
        let newBody = "\(body)\n\n\(hidingContent)"

        let client = Client(
            serverURL: try Servers.server1(),
            transport: URLSessionTransport(),
            middlewares: [AuthenticationMiddleware(token: nil)]
        )

        let comments = try await client.issues_sol_list_hyphen_comments(
            path: .init(owner: owner, repo: repo, issue_number: number)
        ).ok.body.json

        if let comment = comments.first(where: { $0.body?.contains(hidingContent) == true }) {
            _ = try await client.issues_sol_update_hyphen_comment(
                path: .init(owner: owner, repo: repo, comment_id: Components.Parameters.comment_hyphen_id(comment.id)),
                body: .json(.init(body: newBody))
            )
        } else {
            _ = try await client.issues_sol_create_hyphen_comment(
                path: .init(owner: owner, repo: repo, issue_number: number),
                body: .json(.init(body: newBody))
            )
        }
    }
}
`GITHUB_TOKEN` 认证的代码示例。
import Foundation
import GitHubRestAPIUsers
import OpenAPIRuntime
import OpenAPIURLSession
import HTTPTypes

/// Example: ProcessInfo.processInfo.environment["GITHUB_TOKEN"] ?? ""
let token: String = "***"

let client = Client(
    serverURL: try Servers.server1(),
    transport: URLSessionTransport(),
    middlewares: [AuthenticationMiddleware(token: token)]
)

/// Injects an authorization header to every request.
struct AuthenticationMiddleware: ClientMiddleware {

    private let token: String

    init(token: String) {
        self.token = token
    }
    private var header: [String: String] { ["Authorization": "Bearer \(token)" ] }

    func intercept(
        _ request: HTTPRequest,
        body: HTTPBody?,
        baseURL: URL,
        operationID: String,
        next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
    ) async throws -> (HTTPResponse, HTTPBody?) {
        var request = request
        request.headerFields.append(HTTPField(name: .authorization, value: "Bearer \(token)"))
        return try await next(request, body, baseURL)
    }

}

安装

Swift Package Manager

Swift Package Manager 是一种自动化 Swift 代码分发的工具,并且集成在 swift 编译器中。

一旦你设置好你的 Swift 包,添加 github-rest-api-swift-openapi 作为依赖就像添加到你的 Package.swiftdependencies 值一样简单。

// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.

dependencies: [
    .package(url: "https://github.com/wei18/github-rest-api-swift-openapi.git", from: "1.0.0"),
]

概述

OpenAPI 作为一种标准化方式来记录 HTTP 服务。它允许开发者自动化工作流程,例如生成用于发出 HTTP 请求或实现 API 服务器的代码。

Swift OpenAPI Generator 是一个 Swift 包插件,旨在在构建时生成代码,确保它与 OpenAPI 文档保持同步。

使用 子模块 克隆 github/rest-api-description,然后将 openapi 标签拆分为多个模块(Swift Package Products)。

动机

想要使用 Swift 作为开发语言来创建一些方便且用户友好的 GitHub Actions。

贡献

欢迎贡献!如果您遇到问题或有改进建议,请随时打开 issue 或提交 pull request。

此存储库通过子模块 github/rest-api-description 自动保持最新。

如果您发现 GitHub API 的 Swift 代码与这些描述不匹配,或者发现模式格式存在问题,请向 github/rest-api-description 提交一个 issue向 apple/swift-openapi-generator 提交一个 issue