newsapi

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: MIT Imports: 10 Imported by: 1

README

NewsAPI Golang

GoDoc

A simple to use Golang client for the NewsAPI service.

Before you use the package you should read the NewsAPI docs to get familiar with the endpoints and their options.

Install

go get github.com/richarddes/newsapi-golang

Usage

Every project has to first initialize a client obejct with an API key like so:

c := newsapi.Client{APIKey: "your-api-key"}

After that, one of three methods of the Client object can be called. The methods are called TopHeadlines, Everything and Sources. Each one of accepts a context and an options struct which is called exactly like the method plus the word "Opts" at the end. Here's an example of fetching the top headlines from the UK:

ctx := context.Background()

opts := newsapi.TopHeadlinesOpts{
  Country: "uk",
}

r, err := c.TopHeadlines(ctx, opts)
if err != nil {
	log.Fatal(err)
}

When fetching top headlines at least one of the following options must be specified: Q, Category, Country or Sources You also cannot specify the Sources option in conjunction with the Category or Country option.

When fetching everything at least one of the following options must be specified: Q, QInTitle, Sources or Domains

For more details about the options structs please refer to the docs.

Since the TopHeadlines and Everything routes both return a response type of the same underlying type called "articleResp", you can cast them from one to another:

thr := newsapi.TopHeadlinesResp{}
er := newsapi.EverythingResp(t)

The decision to give the two routes different response types has been made to make the API more explicit.

The API also has an "Article" type which represents an article in the "Articles" field of the "TopHeadlinesResp" or "EverythingResp" object. It's useful if, for instance, you want to store the Articles returned by the TopHeadlines and Everything routes in a database. A full example of how to do this can be found down below.
Here's a quick example of how to print the Titles of all articles returned by the TopHeadlines route:

ctx := context.Background()

opts := newsapi.TopHeadlinesOpts{
  Country: "uk",
}

r, err := c.TopHeadlines(ctx, opts)
for _, a in range r.Articles {
	fmt.Println(article.Title)	
}

Full Example

Here's a full runnable example on how to fetch the top headlines in the "business" category and save the recieved articles in a PostgreSQL database.The articles are being saved in a table with following schema:
news(url TEXT PRIMARY KEY, author TEXT, title TEXT, source TEXT)

package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/richarddes/newsapi-golang"
	_ "github.com/lib/pq"
)

func main() {
	db, err := sql.Open("postgres", "user=user password=password host=localhost port=5432")
	if err != nil {
		log.Fatal(err)
	}

	defer db.Close()

	stmt, err := db.Prepare("INSERT INTO news VALUES($1,$2,$3,$4);")
	if err != nil {
		log.Fatal(err)
	}

	defer stmt.Close()

	ctx := context.Background()

	c := newsapi.Client{APIKey: "your-api-key"}
	opts := newsapi.TopHeadlinesOpts{
		Country: "uk",
	}

	r, err := c.TopHeadlines(ctx, opts)
	if err != nil {
		log.Fatal(err)
	}

	for _, article := range r.Articles {
		_, err := stmt.Exec(article.URL, article.Author, article.Title, article.Source)
		if err != nil {
			log.Fatal(err)
		}
	}
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT License. Click here or see the LICENSE file for details.

Documentation

Overview

Package newsapi provides a client library for the "NewsAPI" service. See https://newsapi.org/ for more information.

Every project has to first initialize a client obejct with an API key like so:

c := newsapi.Client{APIKey: "your-api-key"}

After that, one of three methods of the Client object can be called. The methods are called TopHeadlines, Everything and Sources. Each one of them takes in an options struct which is called like the method plus the word "Opts" at the end. Here's an example of fetching the top headlines from the UK:

ctx := context.Background()

opts := newsapi.TopHeadlinesOpts{
	Country: "uk",
}

r, err := c.TopHeadlines(ctx, opts)
if err != nil {
	log.Fatal(err)
}

When fetching top headlines at least one of the following options must be specified: Q, Category, Country or Sources You also cannot specify the Sources option in conjunction with the Category or Country option.

When fetching everything at least one of the following options must be specified: Q, QInTitle, Sources or Domains

Since the TopHeadlines and Everything routes both return a response type of the same underlying type called "articleResp" you can cast them from one to another:

thr := newsapi.TopHeadlinesResp{}
er := newsapi.EverythingResp(t)

The decision to give the two routes different response types has been made to make the API more explicit but this might change in the future.

The API also has an "Article" type which represents an article in the "Articles" field of the "TopHeadlinesResp" or "EverythingResp" object. It's useful if you want to store the Articles returned by the TopHeadlines and Everything routes in a database. For a full example of how to do this, please refer to the github page of this library (https://github.com/richarddes/newsapi-golang). Here's a quick example of how to print the Titles of all articles returned by the TopHeadlines route:

ctx := context.Background()

opts := newsapi.TopHeadlinesOpts{
	Country: "uk",
}

r, err := c.TopHeadlines(ctx, opts)
for _, a in range r.Articles {
	fmt.Println(article.Title)
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAPIKeyDisabled     = errors.New("Your API key has been disabled")
	ErrAPIKeyExhausted    = errors.New("Your API key has no more requests available")
	ErrAPIKeyInvalid      = errors.New("Your API key hasn't been entered correctly. Double check it and try again")
	ErrAPIKeyMissing      = errors.New("Your API key is missing from the request. Append it to the request with one of these methods")
	ErrParameterInvalid   = errors.New("You've included a parameter in your request which is currently not supported. Check the message property for more details")
	ErrParametersMissing  = errors.New("Required parameters are missing from the request and it cannot be completed. Check the message property for more details")
	ErrRateLimited        = errors.New("You have been rate limited. Back off for a while before trying the request again")
	ErrSourcesTooMany     = errors.New("You have requested too many sources in a single request. Try splitting the request into 2 smaller requests")
	ErrSourceDoesNotExist = errors.New("You have requested a source which does not exist")
	ErrUnexpectedError    = errors.New("This shouldn't happen, and if it does then it's our fault, not yours. Try the request again shortly")
)

Functions

This section is empty.

Types

type Article

type Article struct {
	Source      articleSource `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"`
}

The Article type represents an article returned in the "articles" field of the /everything and /top-headliens routes.

type Client

type Client struct {
	APIKey string
}

Client represents the client type for the API. It represents the entry point for the library.

func (*Client) Everything

func (c *Client) Everything(ctx context.Context, opts EverythingOpts) (EverythingResp, error)

Everything fetches the data from the /everything route and returns the response as an EverythingResp object.

func (*Client) Sources

func (c *Client) Sources(ctx context.Context, opts SourcesOpts) (SourcesResp, error)

Sources fetches data from the /sources route and returns the content as a SourcesResp object.

func (*Client) TopHeadlines

func (c *Client) TopHeadlines(ctx context.Context, opts TopHeadlinesOpts) (TopHeadlinesResp, error)

TopHeadlines fetches the data from the /top-headlines route and returns the response as a TopHeadlinesResp object.

type EverythingOpts

type EverythingOpts struct {
	PageSize                         uint8  // cannot be larger than 100 and smaller than 0 so uint8 is sufficient
	Page                             uint16 // unlikely to be larger than ~65k
	Q, QInTitle, Language, SortBy    string
	From, To                         time.Time
	Sources, Domains, ExcludeDomains []string
}

EverythingOpts defines the options for the /everything route.

type EverythingResp

type EverythingResp articleResp

EverythingResp represents what's being returned by the /everything route. It relys on the same underlying type (called articleResp) that the TopHeadlinesResp type relys on. That means that it can easily be casted to the TopHeadlinesResp type.

type SourcesOpts

type SourcesOpts struct {
	Category, Country, Language string
}

SourcesOpts defines the options for the /sources route.

type SourcesResp

type SourcesResp struct {
	Status  string   `json:"status"`
	Sources []source `json:"sources"`
}

SourcesResp represents what's being returned by the /source route.

type TopHeadlinesOpts

type TopHeadlinesOpts struct {
	PageSize             uint8  // cannot be larger than 100 and smaller than 0 so uint8 is sufficient
	Page                 uint16 // unlikely to be larger than ~65k
	Q, Category, Country string
	Sources              []string
}

TopHeadlinesOpts defines the options for the /top-headlines route.

type TopHeadlinesResp

type TopHeadlinesResp articleResp

TopHeadlinesResp represents what's being returned by the /everything route. It relys on the same underlying type (called articleResp) that the EverythingResp type relys on. That means that it can easily be casted to the EverythingResp type.

Jump to

Keyboard shortcuts

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