Skip to content

ralfebert/SweetURLRequest

Repository files navigation

SweetURLRequest

SweetURLRequest simplifies common cases for creating an URLRequest and handling HTTPURLResponse.

Constants for HTTP methods

URLRequest(
    method: .post,
    url: URL(string: "http://www.example.com")!
)

Properties to set common HTTP headers

var request = URLRequest(url: URL(string: "http://www.example.com")!)
request.headers.accept = .json
request.headers.contentType = .xml
request.headers.authorization = "Bearer xyz"

URL/Form/JSON encoded parameters

Parameters will be URL-encoded for GET/HEAD/DELETE and sent as application/x-www-form-urlencoded body for other methods by default:

URLRequest(
    method: .get,
    url: URL(string: "http://www.example.com")!,
    parameters: ["param1" : "äöü", "param2" : "foo bar"]
)

Request with JSON body

You can also pass a body as JSON, this will use JSONEncoder to serialize the given data and set an appropriate Content-Type header:

try URLRequest(
    method: .post,
    url: URL(string: "http://www.example.com")!,
    body: Person(name: "Bob"),
    jsonEncoder: JSONEncoder()
)

Check for a success status code in the 2xx range

func expectSuccess(response: URLResponse) throws {
    let status = (response as! HTTPURLResponse).status
    guard status.responseType == .success else { throw status }
}

Handle HTTP status codes via switch/case, throw a status code as Error

func validate(response: URLResponse) throws {
    let status = (response as! HTTPURLResponse).status

    guard status.responseType == .success else {
        switch status {
        case .unauthorized:
            print("Unauthorized")
        default:
            print("Non-success status: \(status)")
        }
        throw status
    }
}

Example project

MetMuseumEndpoints: A Swift package for the The Metropolitan Museum of Art Collection API

About

SweetURLRequest simplifies common cases for creating an URLRequest and handling HTTPURLResponse.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published