carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
727 stars 41 forks source link

Question: RequestView JSON API #44

Closed ca13ra1 closed 3 years ago

ca13ra1 commented 3 years ago

Having an issue loading JSON data with RequestView. My test data works fine but when I use the API data it's not returning anything. I'm using newsapi.org. I'm getting error RequestError(statusCode: 401, error: Optional(158 bytes)) and my API key is correct.

struct News : Codable {
    var articles : [Article]
}

struct Article : Codable, Hashable {
    let description : String?
    let title : String?
    let author: String?
    let source: Source
    let content: String?
    let publishedAt: String?
}

struct Source: Codable {
    let name: String?
}

struct ContentView: View {

    var body: some View {

        // This works using an example file
        RequestView(News.self, Request {
            Url("https://raw.githubusercontent.com/ca13ra1/data/main/data.json")
            Method(.get)
            Header.Accept(.json)
        }) { news in
            List(news?.articles ?? [], id: \.self) { article in
                Text(article.title ?? "")
            }
            Text("")
        }

        /*
        This does not work
         RequestView(News.self, Request {
             Url("https://newsapi.org/v2/top-headlines?country=us&apiKey=API_KEY")
             Method(.get)
             Header.Accept("application/json")
             Header.ContentType(.json)
             Header.CacheControl(.noCache)
             Header.UserAgent(.safari)
         }) { news in
             List(news?.articles ?? [], id: \.self) { article in
                 Text(article.title ?? "")
             }
             Text("")
         }
        */
    }
}
ca13ra1 commented 3 years ago

Fixed and closing. I forgot to include query strings.

Url("https://newsapi.org/v2/top-headlines")
Query(["country": "us", "apiKey": "API_KEY"])