RealWorld library for open API calls using JavaScript
RealWorld is a fullstack Medium clone that can be written using many different web frameworks. It was developed as a way to show how to accomplish the same website using different backend and frontend technologies.
I created this module as a simple way to interact with the RealWorld API Specification which could be easily dropped in to any frontend technology stack.
Each public function is well-documented in the code using JSDoc and the documentation can be automatically generated using documentation.js.
Unit tests are written to be isolated and idempotent. Addtionally, you do not have to be connected to the internet in order to run the tests. The tests run on an ephemeral local Node.js HTTP server and ensure the API requests are correct.
realworld-api mostly follows the logic of the Tiny Guide to Non Fancy Node, however it makes use of template literals from ES6. If you are bundling realworld-api for use in an older browser that doesn't support template literals, you may want to compile your code using Babel or use a browserify transform such as ES2020.
npm install realworld-api
var RealWorld = require('realworld-api')
var client = new RealWorld()
client.getArticles(function (err, res, data) {
if (err) throw err
console.log(data)
})
- See: RealWorld API Spec
Realworld library for open API calls using JavaScript
Parameters
opts
Object? options for configuring API
Examples
var client = new RealWorld()
var client = new RealWorld({
apiRoot: 'http://localhost:8000/api',
token: 'my-secret-authentication-token'
})
Log in to the RealWorld API
If successful, the data
result will be type {User}
Parameters
opts
Objectcb
RealWorld~requestCallback Callback function
Examples
client.login(
{
email: '[email protected]',
password: 'secret'
},
handleResponse
)
Register a new user with the RealWorld API
Parameters
opts
Objectcb
RealWorld~requestCallback Callback function
Examples
client.register(
{
email: '[email protected]',
password: 'shhhh',
username: 'rick'
},
handleResponse
)
Get the logged in user
Parameters
cb
RealWorld~requestCallback Callback function
Examples
client.getUser(handleResponse)
Update the logged in user info
Parameters
opts
Objectopts.email
string email address of user (optional, defaultnull
)opts.username
string username of user (optional, defaultnull
)opts.bio
string biography of user (optional, defaultnull
)opts.password
string password of user (optional, defaultnull
)opts.image
string url of user image (optional, defaultnull
)
cb
RealWorld~requestCallback Callback function
Examples
client.updateUser(
{
email: '[email protected]',
password: 'hush',
username: 'stace',
bio: 'riot grrl'
},
handleResponse
)
Get profile of a user
Parameters
username
string username of profile to retrievecb
RealWorld~requestCallback Callback function
Examples
client.getProfile('rick', handleResponse)
Follow a user (authentication required)
Parameters
username
string username to followcb
RealWorld~requestCallback Callback function
Examples
client.followUser('rick', handleResponse)
Unfollow a user (authentication required)
Parameters
username
string username to unfollowcb
RealWorld~requestCallback Callback function
Examples
client.unFollowUser('rick', handleResponse)
Request a list of 20 articles sorted by most recent in descending order
Parameters
page
Number page specify which page of articles to show (optional, default0
)cb
RealWorld~requestCallback Callback function
Examples
client.listAllArticles(handleResponse)
client.listAllArticles(2, handleResponse)
Request a list of 10 articles filtered by a tag and sorted by most recent in descending order
Parameters
tag
string tag name to filter bypage
Number specify which page of articles to show (optional, default0
)cb
RealWorld~requestCallback Callback function
Examples
client.listArticlesByTag('JavaScript', handleResponse)
client.listArticlesByTag('JavaScript', 2, handleResponse)
Request a list of five articles filtered by author and sorted by most recent in descending order
Parameters
author
string username of author to filter bypage
Number specify which page of articles to show (optional, default0
)cb
RealWorld~requestCallback Callback function
Examples
client.listArticlesByAuthor('rick', handleResponse)
client.listArticlesByAuthor('rick', 2, handleResponse)
Request a list of 20 articles filtered by author favorites and sorted by most recent in descending order
Parameters
author
string username of author to filter favorite articles bypage
Number specify which page of articles to show (optional, default0
)cb
RealWorld~requestCallback Callback function
Examples
client.listArticlesByAuthorFavorites('rick', handleResponse)
client.listArticlesByAuthorFavorites('rick', 1, handleResponse)
Request a list of ten articles from the currently logged in users feed sorted by most recent in descending order (authentication required)
Parameters
page
Number specify which page of articles to show (optional, default0
)cb
RealWorld~requestCallback Callback function
Examples
client.feedArticles(handleResponse)
client.feedArticles(2, handleResponse)
Request contents from a single article with the specified slug
Parameters
slug
string shortname (slug) of articlecb
RealWorld~requestCallback Callback function
Examples
client.getArticle('angular-app-dev-e33mn9', handleResponse)
Create a new article (authentication required)
Parameters
opts
Objectcb
RealWorld~requestCallback Callback function
Examples
client.createArticle(
{
title: 'My awesome article',
description: 'beep boop',
body: 'wham bam thank you ma\'am',
tagList: ['awesomeness', 'robots']
},
handleResponse
)
Update an existing article with given slug and options (authentication required)
Parameters
slug
string shortname (slug) of article to updateopts
Objectcb
RealWorld~requestCallback Callback function
Examples
client.updateArticle('my-awesome-article-ew9439', {
title: 'my awesome gender neutral article',
description: 'boop beep',
body: 'wham bam thank you friend'
})
Delete an existing article with the given slug (authentication required)
Parameters
slug
string shortname (slug) of article to deletecb
RealWorld~requestCallback Callback function
Examples
client.deleteArticle('my-awesome-article-ew9439', handleResponse)
Add a comment to an article with the given slug (authentication required)
Parameters
slug
string shortname (slug) of article to add comment toopts
Objectopts.body
string content of comment
cb
RealWorld~requestCallback Callback function
Examples
client.addComment(
'my-awesome-article-ew9439',
{
body: 'this is a good article'
},
handleResponse
)
Get comments from an article
Parameters
slug
string shortname (slug) of article from which to retrieve commentscb
RealWorld~requestCallback Callback function
Examples
client.getComments('angular-app-dev-e33mn9', handleResponse)
Delete comment from an article (authentication required)
Parameters
slug
string shortname (slug) of articlecommentId
string unique id of comment to deletecb
RealWorld~requestCallback Callback function
Examples
client.deleteComment('angular-app-dev-e33mn9', 'e11dfeg', handleResponse)
Favorite an article (authentication required)
Parameters
slug
string shortname (slug) of article to favoritecb
RealWorld~requestCallback Callback function
Examples
client.favoriteArticle('my-awesome-article-ew9439', handleResponse)
Unfavorite an article (authentication required)
Parameters
slug
string shortname (slug) of article to unfavoritecb
RealWorld~requestCallback Callback function
Examples
client.unFavoriteArticle('my-awesome-article-ew9439', handleResponse)
Get a list of tags
Parameters
cb
RealWorld~requestCallback Callback function
Examples
client.getTags(handleResponse)
Set the authentication token
Parameters
_token
string authentication token to set
Examples
client.setToken('my-secret-authentication-token')
This callback is displayed as part of the RealWorld class. The error should
be null if the method was able to run. HTTP and API errors are not caught as
errors so that you can catch them yourself. For example, a response code 500
may return (null, { res.statusCode: 500, res.statusMessage: 'Internal Server Error' }, null)
.
API errors are returned with a 422 status code. Errors are included as JSON
in the data
result and are in the form of
{ "errors":{ "body": [ "can't be empty" ] } }
where body
may be any parameter such as password
, email
, etc.
Successful API requests will return JSON data as seen in the RealWorld API Spec
Type: Function
Parameters
err
Error error if method was unable to runres
Object response object from serverdata
Object data result from the server as JSON
Examples
function handleResponse (err, res, data) {
if (err) return console.error(err)
if (res.statusCode === 422 && data.errors) {
Object.keys(data.errors).forEach(function (err) {
var values = data.errors[err]
values.forEach(function (v) {
console.error(`${err} ${v}`)
})
})
return
}
if (res.statusCode !== 200) {
return console.log(`${res.statusCode}: ${res.statusMessage}`)
}
return console.log(data)
}
Copyright 2017 Nick Peihl
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.