newsapi

package module
v0.0.0-...-209e20b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2023 License: MIT Imports: 8 Imported by: 0

README

NewsAPI Go Client

GoDoc Build Status codecov Golangci

Go client for communicating with the newsapi's api.

Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

Prerequisites
go get github.com/egorzot/newsapi

Next, register for free at (https://newsapi.org/register), get yourself a free api key and keep it somewhere safe.

Examples

Retrieving all sources
package main

import (
	"fmt"
	"net/http"
	"context"
	"github.com/egorzot/newsapi"
)

func main() {
	c := newsapi.NewClient("<API KEY>", newsapi.WithHTTPClient(http.DefaultClient))

	sources, err := c.GetSources(context.Background(), nil)

	if err != nil {
		panic(err)
	}

	for _, s := range sources.Sources {
		fmt.Println(s.Description)
	}
}
Retrieving all sources for a specific country (Great Britain in this case)
package main

import (
	"fmt"
	"net/http"
	"context"

	"github.com/egorzot/newsapi"
)

func main() {
	c := newsapi.NewClient("<API KEY>", newsapi.WithHTTPClient(http.DefaultClient))

	sources, err := c.GetSources(context.Background(), &newsapi.SourceParameters{
		Country: "gb",
	})

	if err != nil {
		panic(err)
	}

	for _, s := range sources.Sources {
		fmt.Println(s.Name)
	}
}
Retrieving top headlines
package main

import (
	"fmt"
	"net/http"
	"context"

	"github.com/egorzot/newsapi"
)

func main() {
	c := newsapi.NewClient("<API KEY>", newsapi.WithHTTPClient(http.DefaultClient))

	articles, err := c.GetTopHeadlines(context.Background(), &newsapi.TopHeadlineParameters{
		Sources: []string{ "cnn", "time" },
	})

	if err != nil {
		panic(err)
	}

	for _, s := range articles.Articles {
		fmt.Printf("%+v\n\n", s)
	}
}
Retrieving all articles
package main

import (
	"fmt"
	"net/http"
	"context"

	"github.com/egorzot/newsapi"
)

func main() {
	c := newsapi.NewClient("<API KEY>", newsapi.WithHTTPClient(http.DefaultClient))

	articles, err := c.GetEverything(context.Background(), &newsapi.EverythingParameters{
		Sources: []string{ "cnn", "time" },
	})

	if err != nil {
		panic(err)
	}

	for _, s := range articles.Articles {
		fmt.Printf("%+v\n\n", s)
	}
}

License

This project is licensed under the MIT License

Acknowledgments

  • Inspired by github golang client

Documentation

Overview

Package newsapi provides helper functions to query https://newsapi.org The api maps the responses to appropriate go structs and include all of the possible options

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIError

func APIError(err error) bool

APIError returns if the given err is of type `newsapi.Error`.

Types

type Article

type Article struct {
	Source      Source    `json:"source"`
	Author      string    `json:"author"`
	Title       string    `json:"title"`
	Description string    `json:"description"`
	URL         string    `json:"url"`
	URLToImage  string    `json:"urlToImage"`
	PublishedAt time.Time `json:"publishedAt"`
	Content     string    `json:"content"`
}

Article is a single article from the newsapi article response See http://newsapi.org/docs for more details on the property's

type ArticleResponse

type ArticleResponse struct {
	Status       string    `json:"status"`
	TotalResults int       `json:"totalResults"`
	Articles     []Article `json:"articles"`
}

ArticleResponse is the response from the newsapi article endpoint. Code and Message property will be filled when an error happened. See http://newsapi.org/docs for more details on the property's.

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client manages communication with the NewsAPI API.

func NewClient

func NewClient(apiKey string, options ...OptionFunc) *Client

NewClient returns a new newsapi client to query the newsapi API.

func (*Client) GetEverything

func (c *Client) GetEverything(ctx context.Context, params *EverythingParameters) (*ArticleResponse, error)

GetEverything returns the articles from newsapi See http://newsapi.org/docs for more information It will return the error from newsapi if there is an error

func (*Client) GetSources

func (c *Client) GetSources(ctx context.Context, params *SourceParameters) (*SourceResponse, error)

GetSources returns the sources from newsapi see http://newsapi.org/docs for more information on the parameters

func (*Client) GetTopHeadlines

func (c *Client) GetTopHeadlines(ctx context.Context, params *TopHeadlineParameters) (*ArticleResponse, error)

GetTopHeadlines returns the articles from newsapi See http://newsapi.org/docs for more information It will return the error from newsapi if there is an error

type Error

type Error struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

Error defines an API error from newsapi.

func (Error) Error

func (e Error) Error() string

type EverythingParameters

type EverythingParameters struct {
	Keywords       string   `url:"q,omitempty"`
	Sources        []string `url:"sources,omitempty,comma"`
	Domains        []string `url:"domains,omitempty,comma"`
	ExcludeDomains []string `url:"excludeDomains,omitempty"`
	QInTitle       bool     `url:"qInTitle,omitempty"`

	From time.Time `url:"from,omitempty"`
	To   time.Time `url:"to,omitempty"`

	Language string `url:"language,omitempty"`
	SortBy   string `url:"sortBy,omitempty"`

	Page     int `url:"page,omitempty"`
	PageSize int `url:"pageSize,omitempty"`
}

EverythingParameters are the parameters used for the newsapi everything endpoint.

type OptionFunc

type OptionFunc func(*Client)

OptionFunc is function which modifies the client

func WithBaseURL

func WithBaseURL(url *url.URL) OptionFunc

WithBaseURL sets the baseurl for the newsapi

func WithHTTPClient

func WithHTTPClient(client *http.Client) OptionFunc

WithHTTPClient sets the http client to use when making requests.

func WithUserAgent

func WithUserAgent(userAgent string) OptionFunc

WithUserAgent sets the user agent of the client to userAgent

type Source

type Source struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	URL         string `json:"url"`
	Category    string `json:"category"`
	Language    string `json:"language"`
	Country     string `json:"country"`
	UrlsToLogos struct {
		Small  string `json:"small"`
		Medium string `json:"medium"`
		Large  string `json:"large"`
	} `json:"urlsToLogos"`
}

Source is a source from newsapi it contains all the information provided by the api

type SourceParameters

type SourceParameters struct {
	Category string `url:"category,omitempty"`
	Language string `url:"language,omitempty"`
	Country  string `url:"country,omitempty"`
}

SourceParameters are the parameters which can be used in the source request to newsapi

type SourceResponse

type SourceResponse struct {
	Status  string   `json:"status"`
	Sources []Source `json:"sources"`
}

SourceResponse is the response from the source request

type TopHeadlineParameters

type TopHeadlineParameters struct {
	Country  string   `url:"country,omitempty"`
	Category string   `url:"category,omitempty"`
	Sources  []string `url:"sources,omitempty,comma"`
	Keywords string   `url:"q,omitempty"`
	Page     int      `url:"page,omitempty"`
	PageSize int      `url:"pageSize,omitempty"`
}

TopHeadlineParameters are the parameters which can be used to tweak to request for the top headlines.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL