Swiftpack.co - Package - kylejohnsonkj/swift-nio-http2-demo


Project demonstrating the creation of a RESTful web service using apple/swift-nio-http2.

Getting Started

Firstly, ensure nghttp2 is installed. You can do so via Homebrew.

$ brew install nghttp2

Next, clone the repository and open the .xcodeproj after it's generated.

$ git clone https://github.com/kylejohnsonkj/swift-nio-http2-demo.git
$ cd swift-nio-http2-demo/
$ swift package generate-xcodeproj
$ open myserver.xcodeproj/

Ensure myserver is selected as scheme and that My Mac is set as the target device. The server is now ready to be built and run. Do so either through Xcode or by running the shell command from the project directory (port will be 8889 throughout this demo).

$ swift run myserver localhost 8889


Using cURL

At the present time, swift-nio-http2 does not know how to negotiate HTTP/2. You must hit it with curl like so:

$ curl --http2-prior-knowledge http://localhost:8889/

Note: I've turned on verbose mode (-v) for the remainder of this demo. Basic authentication is also included. Therefore, all commands must include valid user credentials (-u), amending the above command to the following.

$ curl -vu 'user:pass' --http2-prior-knowledge http://localhost:8889/

This server features the 4 basic methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests. The details of how to use these methods with the example Person object will be demonstrated below.

PUT (create)

Creates a person object from provided JSON data.

$ curl -vu 'user:pass' --http2-prior-knowledge http://localhost:8889/persons --data '{"name":"Kyle","age":21}' -XPUT

All object properties must be included in JSON format for the object to be created (with the exception of id, which is generated by the server).

GET (retrieve)

Retrieves all persons in JSON format matching the given query.

$ curl -vu 'user:pass' --http2-prior-knowledge http://localhost:8889/persons

Supports queries for equality on all struct properties (ex. /persons?id=0, /persons?name=Kyle, /persons?age=21)

For multiple queries, tag on using "&" and include single quotes around the whole uri.

$ curl -vu 'user:pass' --http2-prior-knowledge 'http://localhost:8889/persons?age=21&name=Kyle'

PATCH (update)

$ curl -vu 'user:pass' --http2-prior-knowledge http://localhost:8889/persons/0 --data '{"name":"Kylo Ren"}' -XPATCH

All properties can be modified via JSON, with the exception of id, which is immutable.

Note: Only one resource can be updated per request. Resource count can be limited by querying or by supplying an object record like so: /persons/{id}

DELETE (delete)

$ curl -vu 'user:pass' --http2-prior-knowledge http://localhost:8889/persons/0 -XDELETE

Note: Similarly to PATCH, only one resource can be deleted per request.


Stars: 3
Help us keep the lights on


Used By

Total: 0