UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to load a JSON file in Vapor 4?

Forums > Server-side Swift

Hi amazing Hacking with Swift community,

I am building a project with Vapor 4. I have a .json file with my data saved in the Public folder, how can I load this data using vapor and get the response?

I created an example of the json file and I am able to get the response. What I am having issues is to locate the file in the Public folder and decode the data.

I did enabled the middleware, see below:

import Vapor

// configures your application
public func configure(_ app: Application) throws {

    app.http.server.configuration.hostname = "192.168.1.123"
    app.http.server.configuration.port = 8888

    app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))

    // register routes
    try routes(app)
}

Here is the code with the JSON example:

import Foundation
import Vapor

struct Event: Content {

    let id: Int
    let date: String
    let event: String
    let title: String
    let description: String

}

struct APIController: RouteCollection {

    func boot(routes: RoutesBuilder) throws {
        let api = routes.grouped("api")
        api.get("events", use: getEvents)
    }

    func getEvents(req: Request) throws -> Response {

    let events = [
    [
      "id": 1,
      "date": "1/2/2022",
      "event": "New Moon",
      "title": "New Moon",
      "description": "The Moon will located on the same side of the Earth as the Sun and will not be visible in the night sky. This phase occurs at 18:35 UTC. This is the best time of the month to observe faint objects such as galaxies and star clusters because there is no moonlight to interfere."
    ],
    [
      "id": 2,
      "date": "1/3/2022",
      "event": "Meteor Shower",
      "title": "Quadrantids Meteor Shower",
      "description": "The Quadrantids is an above average shower, with up to 40 meteors per hour at its peak. It is thought to be produced by dust grains left behind by an extinct comet known as 2003 EH1, which was discovered in 2003. The shower runs annually from January 1-5. It peaks this year on the night of the 3rd and  morning of the 4th. The thin, crescent moon will set early in the evening leaving dark skies for what should be an excellent show. Best viewing will be from a dark location after midnight. Meteors will radiate from the constellation Bootes, but can appear anywhere in the sky."
    ],
    [
      "id": 3,
      "date": "1/7/2022",
      "event": "Planetary Event",
      "title": "Mercury at Greatest Eastern Elongation",
      "description": "The planet Mercury reaches greatest eastern elongation of 19.2 degrees from the Sun. This is the best time to view Mercury since it will be at its highest point above the horizon in the evening sky. Look for the planet low in the western sky just after sunset."
    ]
    ]
    let data = try JSONSerialization.data(withJSONObject: events, )
    return Response(status: .ok, body: Response.Body(data: data))    

    }

}

Thanks a lot, Renato.

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.