newsapi

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2022 License: MIT Imports: 9 Imported by: 0

README

newsapi

GoDoc Test coverage Go Report Card

Go client implementation for the NewsAPI.

Installation

go get github.com/jellydator/newsapi-go

Usage

Simply, we create a client using NewClient function, by default only an API key is required, however some other parameters can be set using variadic option functions.

client := newsapi.NewClient("apiKey", newsapi.WithHTTPClient(&http.Client{
	Timeout: 5 * time.Second,
}))

Endpoints

Everything

Everything retrieves all articles based on provided parameters. Full endpoint documentation can be viewed here.

articles, pageCount, err := client.Everything(context.Background(), newsapi.EverythingParams{
	Query: "cryptocurrency",
})
if err != nil {
	// handle error
}
// success
Top Headlines

TopHeadlines retrieves top headlines articles based on provided parameters. Full endpoint documentation can be viewed here.

articles, pageCount, err := client.TopHeadlines(context.Background(), newsapi.TopHeadlinesParams{
	Query: "cryptocurrency",
})
if err != nil {
	// handle error
}
// success
Sources

Sources retrieves available sources based on provided parameters. Full endpoint documentation can be viewed here.

sources, err := client.Sources(context.Background(), newsapi.SourceParams{
	Categories: []newsapi.Category{
		newsapi.CategoryBusiness,
		newsapi.CategoryScience,
	},
})
if err != nil {
	// handle error
}
// success

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidQueryLength is returned whenever query length exceeds
	// maximum characters size, which is 500.
	ErrInvalidQueryLength = errors.New("query exceeds 500 character limit")

	// ErrInvalidSearchIn is returned whenever search in type has a value
	// that is not predefined list.
	ErrInvalidSearchIn = errors.New("invalid search key")

	// ErrInvalidFromTime is returned whenever from and to times are used
	// and to is earlier than the from time.
	ErrInvalidFromTime = errors.New("from time cannot be after to time")

	// ErrInvalidCategory is returned whenever category type has a value
	// that is not in the predefined list.
	ErrInvalidCategory = errors.New("invalid category")

	// ErrInvalidLanguage is returned whenever language type has a value
	// that is not in the predefined list.
	ErrInvalidLanguage = errors.New("invalid language")

	// ErrInvalidCountry is returned whenever country type has a value
	// that is not in the predefined list.
	ErrInvalidCountry = errors.New("invalid country")

	// ErrInvalidSortBy is returned whenever sort by type has a value
	// that is not in the predefined list.
	ErrInvalidSortBy = errors.New("invalid sort key")

	// ErrInvalidPageSize is returned whenever page size exceeds a
	// maximum of 100 entries.
	ErrInvalidPageSize = errors.New("page size exceeds 100 entries limit")

	// ErrIncompatibleParams is returned whenever in TopHeadlinesParams
	// parameters sources is used along with country or category.
	ErrIncompatibleParams = errors.New("country/category parameter cannot be used along with sources parameter")

	// ErrTooManySources is returned whenever sources list exceeds 20
	// entries.
	ErrTooManySources = errors.New("sources exceeds 20 entries limit")

	// ErrParamsScopeTooBroad is returned when the scope of parameters is
	// too broad.
	ErrParamsScopeTooBroad = errors.New("scope of parameters is too broad")
)

Functions

This section is empty.

Types

type Article

type Article struct {
	// SourceID specifies source identifying information.
	Source SourceID `json:"source"`

	// Author specifies the author of the article.
	Author string `json:"author"`

	// Title specifies the title/headline of the article.
	Title string `json:"title"`

	// Description specifies short summary of the article.
	Description string `json:"description"`

	// URL specifies the url of the article.
	URL string `json:"url"`

	// URLToImage specifies url to the article image.
	URLToImage string `json:"urlToImage"`

	// PublishedAt specifies the date and time at which the article
	// was published.
	PublishedAt time.Time `json:"publishedAt"`

	// Content specifies an unformatted text of the article. It is
	// truncated to 200 chars.
	Content string `json:"content"`
}

Article contains information of a specific news publisher article.

type Category

type Category string

Category determines the category of the source.

const (
	CategoryBusiness      Category = "business"
	CategoryEntertainment Category = "entertainment"
	CategoryGeneral       Category = "general"
	CategoryHealth        Category = "health"
	CategoryScience       Category = "science"
	CategorySports        Category = "sports"
	CategoryTechnology    Category = "technology"
)

All available categories.

type Client

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

Client handles request sending to newsapi.

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient creates a fresh instance of newsapi client.

func (*Client) Everything

func (c *Client) Everything(ctx context.Context, pr EverythingParams) ([]Article, uint, error)

Everything retrieves articles by the provided parameters. The uint return value indicates the number of available articles. The length of the returned slice may be less than this value; additional calls need to be made to retrieve other available articles. Endpoint documentation can be found here: https://newsapi.org/docs/endpoints/everything

func (*Client) Sources

func (c *Client) Sources(ctx context.Context, pr SourceParams) ([]Source, error)

Sources retrieves available sources for top headlines and everything endpoints by the provided parameters. Endpoint documentation can be found here: https://newsapi.org/docs/endpoints/sources

func (*Client) TopHeadlines

func (c *Client) TopHeadlines(ctx context.Context, pr TopHeadlinesParams) ([]Article, uint, error)

TopHeadlines retrieves top headlines articles by the provided parameters. The uint return value indicates the number of available articles. The length of the returned slice may be less than this value; additional calls need to be made to retrieve other available articles. Endpoint documentation can be found here: https://newsapi.org/docs/endpoints/top-headlines

type ClientOption

type ClientOption func(c *Client)

ClientOption is used to set client configuration options.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL sets custom base url.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) ClientOption

WithHTTPClient sets custom http client.

type Country

type Country string

Country determines the origin of the source.

const (
	CountryUnitedArabEmirates Country = "ae"
	CountryArgentina          Country = "ar"
	CountryAustria            Country = "at"
	CountryAustralia          Country = "au"
	CountryBelgium            Country = "be"
	CountryBulgaria           Country = "bg"
	CountryBrazil             Country = "br"
	CountryCanada             Country = "ca"
	CountrySwitzerland        Country = "ch"
	CountryChina              Country = "cn"
	CountryColombia           Country = "co"
	CountryCuba               Country = "cu"
	CountryCzechia            Country = "cz"
	CountryGermany            Country = "de"
	CountryEgypt              Country = "eg"
	CountryFrance             Country = "fr"
	CountryUnitedKingdom      Country = "gb"
	CountryGreece             Country = "gr"
	CountryHonkKong           Country = "hk"
	CountryHungary            Country = "hu"
	CountryIndonesia          Country = "id"
	CountryIreland            Country = "ie"
	CountryIsrael             Country = "il"
	CountryIndia              Country = "in"
	CountryItaly              Country = "it"
	CountryJapan              Country = "jp"
	CountryKorea              Country = "kr"
	CountryLithuania          Country = "lt"
	CountryLatvia             Country = "lv"
	CountryMorocco            Country = "ma"
	CountryMexico             Country = "mx"
	CountryMalaysia           Country = "my"
	CountryNigeria            Country = "ng"
	CountryNetherlands        Country = "nl"
	CountryNorway             Country = "no"
	CountryNewZealand         Country = "nz"
	CountryPhilippines        Country = "ph"
	CountryPoland             Country = "pl"
	CountryPortugal           Country = "pt"
	CountryRomania            Country = "ro"
	CountrySerbia             Country = "rs"
	CountryRussia             Country = "ru"
	CountrySaudiArabia        Country = "sa"
	CountrySweden             Country = "se"
	CountrySingapore          Country = "sg"
	CountrySlovenia           Country = "si"
	CountrySlovakia           Country = "sk"
	CountryThailand           Country = "th"
	CountryTurkey             Country = "tr"
	CountryTaiwan             Country = "tw"
	CountryUkraine            Country = "ua"
	CountryUnitedStates       Country = "us"
	CountryVenezuela          Country = "ve"
	CountrySouthAfrica        Country = "za"
)

All available countries.

type Error

type Error struct {
	// HTTPCode specifies the response status code.
	HTTPCode int

	// APICode specifies the error code returned from newsapi.
	APICode string

	// Message specifies the error message returned from newsapi.
	Message string
}

Error contains newsapi error information.

func (*Error) Error

func (e *Error) Error() string

Error implements error interface and returns formatted error message.

type EverythingParams

type EverythingParams struct {
	// Query is used to filter articles' text. An advanced search is
	// allowed:
	// * Phrases that must be matched exactly as is should be surrounded
	//   with quotes ("). e.g "my short phrase"
	// * Words or phrases that must appear in an article should be
	//   prefixed with a plus (+) sign. e.g +bitcoin.
	// * Words or phrases that must not appear in an article should be
	//   prefixed with a minus (-) sign. e.g -bitcoin.
	// * "AND", "OR" and "NOT" keywords can be used to group several
	//   queries. Parenthesis can be used to create subgroups. e.g:
	//   crypto AND (ethereum OR litecoin) NOT bitcoin.
	// Query has a maximum length of 500 characters.
	Query string

	// QueryInTitle is used to filter article title. Unlike query
	// parameter it doesn't allow for an advanced search, so only basic
	// keywords or phrases should be used.
	QueryInTitle string

	// SearchIn specifies which part of an article should be searched.
	SearchIn SearchIn

	// Sources is used to filter news publishers. The list of available
	// sources can be retrieved using Sources method on a client or by
	// looking at the sources index here:
	// https://newsapi.org/sources
	// 20 is the maximum sources allowed.
	Sources []string

	// Domains is used to restrict the search to the specified domains.
	Domains []string

	// ExcludeDomains is used to remove results that contain specified
	// domains.
	ExcludeDomains []string

	// From is a date and time for the oldest allowed article.
	From time.Time

	// To is a date and time for the newest allowed article.
	To time.Time

	// Language is used to filter articles by language. If
	// left empty all languages are used.
	Language Language

	// SortBy specifies a key by which articles should be sorted.
	SortBy SortBy

	// PageSize specifies the total number of results to return per page.
	// 20 is default, 100 is the maximum.
	PageSize uint

	// Page pages through results if the total results found is greater
	// than the page size.
	Page uint
}

EverythingParams contains everything endpoint filters. Original documentation can be found here: https://newsapi.org/docs/endpoints/everything

type Language

type Language string

Language determines the language of the source.

const (
	LanguageArabic    Language = "ar"
	LanguageGerman    Language = "de"
	LanguageEnglish   Language = "en"
	LanguageSpanish   Language = "es"
	LanguageFrench    Language = "fr"
	LanguageHebrew    Language = "hr"
	LanguageItalian   Language = "it"
	LanguageDutch     Language = "nl"
	LanguageNorwegian Language = "no"
	LanguagePortugese Language = "pt"
	LanguageRussian   Language = "ru"
	LanguageSami      Language = "se"
	LanguageUrdu      Language = "ud"
	LanguageChinese   Language = "zh"
)

All available languages.

type SearchIn

type SearchIn string

SearchIn determines in which article part newsapi should search.

const (
	SearchInTitle       SearchIn = "title"
	SearchInDescription SearchIn = "description"
	SearchInContent     SearchIn = "content"
)

All available search keys.

type SortBy

type SortBy string

SortBy determines newsapi result order.

const (
	SortByRelevancy   SortBy = "relevancy"
	SortByPopularity  SortBy = "popularity"
	SortByPublishedAt SortBy = "publishedAt"
)

All available sort keys.

type Source

type Source struct {
	SourceID

	// Description specifies short introduction about the news source.
	Description string `json:"description"`

	// URL specifies the url of the news source.
	URL string `json:"url"`

	// Category specifies the type of news that this source produces.
	Category Category `json:"category"`

	// Language specifies the language in which the news source
	// publishes.
	Language Language `json:"language"`

	// Country specifies the country in which the news source publishes.
	Country Country `json:"country"`
}

Source contains information about news publisher.

type SourceID

type SourceID struct {
	// ID is the identifier of the news source.
	ID string `json:"id"`

	// Name of the news source.
	Name string `json:"name"`
}

SourceID contains identifying information of a news publisher.

type SourceParams

type SourceParams struct {
	// Categories is used to filter sources by categories. If left empty
	// all categories are used.
	Categories []Category

	// Languages is used to filter sources by languages. If left empty
	// all languages are used.
	Languages []Language

	// Countries is used to filter sources by countries. If left empty
	// all countries are used.
	Countries []Country
}

SourceParams contains source endpoint filters.

type TopHeadlinesParams

type TopHeadlinesParams struct {
	// Query is used to filter articles' text. Unlike Everything endpoint
	// parameters it doesn't allow for an advanced search, so only basic
	// keywords or phrases should be used. Query has a maximum length of
	// 500 characters.
	Query string

	// Category is used to filter articles by category. If left
	// empty all categories are used.
	Category Category

	// Language is used to filter articles by language. If
	// left empty all languages are used.
	Language Language

	// Country is used to filter articles by country. If left empty
	// all countries are used.
	Country Country

	// Sources is used to filter news publishers. The list of available
	// sources can be retrieved using Sources method on a client or by
	// looking at the sources index here:
	// https://newsapi.org/sources
	Sources []string

	// PageSize specifies the total number of results to return per page.
	// 20 is default, 100 is the maximum.
	PageSize uint

	// Page pages through results if the total results found is greater
	// than the page size.
	Page uint
}

TopHeadlinesParams contains top headlines endpoint filters.

Jump to

Keyboard shortcuts

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