Introducing Swift HTTP Types
Swift HTTP Types is an open source package that provides a shared set of currency types for client/server HTTP operations in Swift. It aims to offer a common representation of the core building blocks of HTTP messages, such as HTTPRequest and HTTPResponse, which can be adopted across multiple projects. By using these types, developers can share more code between clients and servers, eliminating the need for type conversions when working with different frameworks.
The package focuses on modern HTTP versions like HTTP/3 and HTTP/2, while also maintaining compatibility with HTTP/1.1. As it matures, the goal is to replace SwiftNIO's HTTPRequestHead and HTTPResponseHead, as well as the HTTP message details of Foundation's URLRequest and URLResponse.
With Swift HTTP Types, developers can perform common HTTP operations in an ergonomic way. For example, creating an HTTP request is straightforward:
let request = HTTPRequest(method: .get, url: URL(string: "https://www.example.com")!)
Modifying the request is also easy:
request.method = .post
request.url = URL(string: "https://www.example.com/newpath")!
Creating an HTTP response is similarly simple:
let response = HTTPResponse(statusCode: 200, body: "Hello, world!")
Header fields can be accessed and modified using the headerFields
property:
request.headerFields["Content-Type"] = "application/json"
The package includes common header fields, and developers can easily add extensions for custom header fields and values.
Swift HTTP Types is designed to be suitable for use in any HTTP scenario and is not tied to any specific framework, eliminating the need for duplicate HTTP abstractions. It provides a convenient and efficient way for developers to work with HTTP in Swift, whether they are building client or server applications.