To return a JSON response from a Vapor
HTTP server in Swift
, first, you need to create a struct
or class
that represents the data you want to return as JSON.
For example, let's create a Student
struct:
main.swift82 chars6 lines
Here, Content
is a protocol provided by Vapor
, which indicates that this struct
can be easily converted to and from various formats including JSON
.
Next, you can create a route handler that returns the Student
data as JSON. Inside the route handler, create an instance of Student
and then return it as a Response
.
main.swift170 chars7 lines
This route handler returns an instance of Student
directly. However, if you need to perform some additional processing on the data before returning it, you can encode the data as JSON
first and then return it as Data
wrapped in a Response
object.
main.swift233 chars8 lines
Here, JSONEncoder()
is used to encode the Student
instance as JSON
, and then it is returned as Data
wrapped in a Response
object.
Finally, register the route handler in your application's router:
main.swift123 chars9 lines
With this setup, when you send a GET
request to the /student
endpoint, it will return the Student
data as a JSON
response.
gistlibby LogSnag