Edward Jackson

Edward Jackson

1558857019

Creating RESTful APIs with NodeJS and MongoDB Tutorial

Welcome to this tutorial about RESTful API using Node.js (Express.js) and MongoDB (mongoose)! We are going to learn how to install and use each component individually and then proceed to create a RESTful API.

MEAN Stack tutorial series:

  1. AngularJS tutorial for beginners (Part I)
  2. Creating RESTful APIs with NodeJS and MongoDB Tutorial (Part II) 👈 you are here
  3. MEAN Stack Tutorial: MongoDB, ExpressJS, AngularJS and NodeJS (Part III)

1. What is a RESTful API?

REST stands for Representational State Transfer. It is an architecture that allows client-server communication through a uniform interface. REST is stateless, cachable and has property called idempotence. It means that the side effect of identical requests have the same side-effect as a single request.

HTTP RESTful API’s are compose of:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

Here is a summary what we want to implement:

NOTE for this tutorial:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

2. Installing the MEAN Stack Backend

In this section, we are going to install the backend components of the MEAN stack: MongoDB, NodeJS and ExpressJS. If you already are familiar with them, then jump to wiring the stack. Otherwise, enjoy the ride!

2.1 Installing MongoDB

MongoDB is a document-oriented NoSQL database (Big Data ready). It stores data in JSON-like format and allows users to perform SQL-like queries against it.

You can install MongoDB following the instructions here.

If you have a Mac and brew it’s just:

	

brew install mongodb && mongod

In Ubuntu:

sudo apt-get -y install mongodb

After you have them installed, check version as follows:

# Mac
mongod --version
# => db version v2.6.4
# => 2014-10-01T19:07:26.649-0400 git version: nogitversion

# Ubuntu
mongod --version
# => db version v2.0.4, pdfile version 4.5
# => Wed Oct  1 23:06:54 git version: nogitversion

2.2 Installing NodeJS

The Node official definition is:

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.> Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
In short, NodeJS allows you to run Javascript outside the browser, in this case, on the web server. NPM allows you to install/publish node packages with ease.

To install it, you can go to the NodeJS Website.

Since Node versions changes very often. You can use the NVM (Node Version Manager) on Ubuntu and Mac with:

# download NPM
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.4/install.sh | bash

# load NPM
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

# Install latest stable version
nvm install stable

Check out https://github.com/creationix/nvm for more details.

Also, on Mac and brew you can do:

brew install nodejs

After you got it installed, check node version and npm (node package manager) version:

node -v
# => v6.2.2

npm -v
# => 3.9.5

2.3 nstalling ExpressJS

ExpressJS is a web application framework that runs on NodeJS. It allows you to build web applications and API endpoints. (more details on this later).

We are going to create a project folder first, and then add express as a dependency. Let’s use NPM init command to get us started.

# create project folder
mkdir todo-app

# move to the folder and initialize the project
cd todo-app
npm init .  # press enter multiple times to accept all defaults

# install express v4.14 and save it as dependency
npm install express@4.14 --save

Notice that after the last command, express should be added to package.json with the version 4.14.x.

3. Using MongoDB with Mongoose

Mongoose is an NPM package that allows you to interact with MongoDB. You can install it as follows:

npm install mongoose@4.5.8 --save

If you followed the previous steps, you should have all you need to complete this tutorial. We are going to build an API that allow users to CRUD (Create-Read-Update-Delete) Todo tasks from database.

3.1 Mongoose CRUD

CRUD == Create-Read-Update-Delete

We are going to create, read, update and delete data from MongoDB using Mongoose/Node. First, you need to have mongodb up and running:

# run mongo daemon
mongod

Keep mongo running in a terminal window and while in the folder todoApp type node to enter the node CLI. Then:

// Load mongoose package
var mongoose = require('mongoose');

// Connect to MongoDB and create/use database called todoAppTest
mongoose.connect('mongodb://localhost/todoAppTest');

// Create a schema
var TodoSchema = new mongoose.Schema({
  name: String,
  completed: Boolean,
  note: String,
  updated_at: { type: Date, default: Date.now },
});

// Create a model based on the schema
var Todo = mongoose.model('Todo', TodoSchema);

Great! Now, let’s test that we can save and edit data.

3.2 Mongoose Create

// Create a todo in memory
var todo = new Todo({name: 'Master NodeJS', completed: false, note: 'Getting there...'});

// Save it to database
todo.save(function(err){
  if(err)
    console.log(err);
  else
    console.log(todo);
});

If you take a look to Mongo you will notice that we just created an entry. You can easily visualize data using Robomongo:

You can also build the object and save it in one step using create:

Todo.create({name: 'Create something with Mongoose', completed: true, note: 'this is one'}, function(err, todo){
  if(err) console.log(err);
  else console.log(todo);
});

3.3 Mongoose Read and Query

So far we have been able to save data, now we are going explore how to query the information. There are multiple options for reading/querying data:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

Some examples:

// Find all data in the Todo collection
Todo.find(function (err, todos) {
  if (err) return console.error(err);
  console.log(todos)
});

The result is something like this:

[ { _id: 57a6116427f107adef36c2f2,
    name: 'Master NodeJS',
    completed: false,
    note: 'Getting there...',
    __v: 0,
    updated_at: 2016-08-06T16:33:40.606Z },
  { _id: 57a6142127f107adef36c2f3,
    name: 'Create something with Mongoose',
    completed: true,
    note: 'this is one',
    __v: 0,
    updated_at: 2016-08-06T16:45:21.143Z } ]

You can also add queries

// callback function to avoid duplicating it all over
var callback = function (err, data) {
  if (err) { return console.error(err); }
  else { console.log(data); }
}

// Get ONLY completed tasks
Todo.find({completed: true }, callback);

// Get all tasks ending with `JS`
Todo.find({name: /JS$/ }, callback);

You can chain multiple queries, e.g.:

var oneYearAgo = new Date();
oneYearAgo.setYear(oneYearAgo.getFullYear() - 1);

// Get all tasks staring with `Master`, completed
Todo.find({name: /^Master/, completed: true }, callback);

// Get all tasks staring with `Master`, not completed and created from year ago to now...
Todo.find({name: /^Master/, completed: false }).where('updated_at').gt(oneYearAgo).exec(callback);

MongoDB query language is very powerful. We can combine regular expressions, date comparison and more!

3.4 Mongoose Update

Moving on, we are now going to explore how to update data.

Each model has an update method which accepts multiple updates (for batch updates, because it doesn’t return an array with data).

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

Alternatively, the method findOneAndUpdate could be used to update just one and return an object.

// Model.update(conditions, update, [options], [callback])
// update `multi`ple tasks from complete false to true

Todo.update({ name: /master/i }, { completed: true }, { multi: true }, callback);

//Model.findOneAndUpdate([conditions], [update], [options], [callback])
Todo.findOneAndUpdate({name: /JS$/ }, {completed: false}, callback);

As you might noticed the batch updates (multi: true) doesn’t show the data, rather shows the number of fields that were modified.

{ ok: 1, nModified: 1, n: 1 }

Here is what they mean:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

3.5 Mongoose Delete

update and remove mongoose API are identical, the only difference it is that no elements are returned. Try it on your own ;)

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

4. ExpressJS and Middlewares

ExpressJS is a complete web framework solution. It has HTML template solutions (jade, ejs, handlebars, hogan.js) and CSS precompilers (less, stylus, compass). Through middlewares layers, it handles: cookies, sessions, caching, CSRF, compression and many more.

Middlewares are pluggable processors that runs on each request made to the server. You can have any number of middlewares that will process the request one by one in a serial fashion. Some middlewares might alter the request input. Others, might create log outputs, add data and pass it to the next() middleware in the chain.

We can use the middlewares using app.use. That will apply for all request. If you want to be more specific, you can use app.verb. For instance: app.get, app.delete, app.post, app.update, …

Let’s give some examples of middlewares to drive the point home.

Say you want to log the IP of the client on each request:

app.use(function (req, res, next) {
  var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  console.log('Client IP:', ip);
  next();
});

Notice that each middleware has 3 parameters:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

You can also specify a path that you want the middleware to activate on.

Middleware mounted on "/todos/:id" and log the request method

app.use('/todos/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

And finally you can use app.get to catch GET requests with matching routes, reply the request with a response.send and end the middleware chain. Let’s use what we learned on mongoose read to reply with the user’s data that matches the id.

Middleware mounted on "/todos/:id" and returns

app.get('/todos/:id', function (req, res, next) {
  Todo.findById(req.params.id, function(err, todo){
    if(err) res.send(err);
    res.json(todo);
  });
});

Notice that all previous middlewares called next() except this last one, because it sends a response (in JSON) to the client with the requested todo data.

Hopefully, you don’t have to develop a bunch of middlewares besides routes, since ExpressJS has a bunch of middlewares available.

4.1 Default Express 4.0 middlewares

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

4.2 Other ExpressJS Middlewares

The following middlewares are not added by default, but it’s nice to know they exist at least:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

5. Wiring up the MEAN Stack

In the next sections, we are going to put together everything that we learn from and build an API. They can be consume by browsers, mobile apps and even other servers.

5.1 Bootstrapping ExpressJS

After a detour in the land of Node, MongoDB, Mongoose, and middlewares, we are back to our express todoApp. This time to create the routes and finalize our RESTful API.

Express has a separate package called express-generator, which can help us to get started with out API.

# install it globally using -g
npm install express-generator -g

# create todo-app API with EJS views (instead the default Jade)
express todo-api -e

#   create : todo-api
#   create : todo-api/package.json
#   create : todo-api/app.js
#   create : todo-api/public
#   create : todo-api/public/javascripts
#   create : todo-api/routes
#   create : todo-api/routes/index.js
#   create : todo-api/routes/users.js
#   create : todo-api/public/stylesheets
#   create : todo-api/public/stylesheets/style.css
#   create : todo-api/views
#   create : todo-api/views/index.ejs
#   create : todo-api/views/layout.ejs
#   create : todo-api/views/error.ejs
#   create : todo-api/public/images
#   create : todo-api/bin
#   create : todo-api/bin/www
#
#   install dependencies:
#     $ cd todo-api && npm install
#
#   run the app on Linux/Mac:
#     $ DEBUG=todo-app:* npm start
#
#   run the app on Windows:
#     $ SET DEBUG=todo-api:* & npm start

This will create a new folder called todo-api. Let’s go ahead and install the dependencies and run the app:

# install dependencies
cd todo-api && npm install

# run the app on Linux/Mac
PORT=4000 npm start

# run the app on Windows
SET PORT=4000 & npm start

Use your browser to go to http://0.0.0.0:4000, and you should see a message “Welcome to Express”

5.2 Connect ExpressJS to MongoDB

In this section we are going to access MongoDB using our newly created express app. Hopefully, you have installed MongoDB in the setup section, and you can start it by typing (if you haven’t yet):

mongod

Install the MongoDB driver for NodeJS called mongoose:

npm install mongoose --save

Notice --save. It will add it to the todo-api/package.json

Next, you need to require mongoose in the todo-api/app.js

// load mongoose package
var mongoose = require('mongoose');

// Use native Node promises
mongoose.Promise = global.Promise;

// connect to MongoDB
mongoose.connect('mongodb://localhost/todo-api')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));

Now, When you run npm start or ./bin/www, you will notice the message connection successful. Great!

You can find the repository here and the diff code at this point: diff

5.3 Creating the Todo model with Mongoose

It’s show time! All the above was setup and preparation for this moment. Let bring the API to life.

Create a models directory and a Todo.js model:

mkdir models
touch models/Todo.js

In the models/Todo.js:

var mongoose = require('mongoose');

var TodoSchema = new mongoose.Schema({
  name: String,
  completed: Boolean,
  note: String,
  updated_at: { type: Date, default: Date.now },
});

module.exports = mongoose.model('Todo', TodoSchema);

diff

What’s going on up there? Isn’t MongoDB suppose to be schemaless? Well, it is schemaless and very flexible indeed. However, very often we want bring sanity to our API/WebApp through validations and enforcing a schema to keep a consistent structure. Mongoose does that for us, which is nice.

You can use the following types:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

6. API clients (Browser, Postman and curl)

I know you have not created any route yet. However, in the next sections you will. These are just three ways to retrieve, change and delete data from your future API.

6.1 Curl

# Create task
curl -XPOST http://localhost:3000/todos -d 'name=Master%20Routes&completed=false&note=soon...'

# List tasks
curl -XGET http://localhost:3000/todos

6.2 Browser and Postman

If you open your browser and type localhost:3000/todos you will see all the tasks (when you implement it). However, you cannot do post commands by default. For further testing let’s use a Chrome plugin called Postman. It allows you to use all the HTTP VERBS easily and check x-www-form-urlencoded for adding parameters.

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.## 6.3 Websites and Mobile Apps

Probably these are the main consumers of APIs. You can interact with RESTful APIs using jQuery’s $ajax and its wrappers, BackboneJS’s Collections/models, AngularJS’s $http or $resource, among many other libraries/frameworks and mobile clients.

In the end, we are going to explain how to use AngularJS to interact with this API.

7. ExpressJS Routes

To sum up we want to achieve the following:

Let’s setup the routes

mv routes/users.js routes/todos.js

In app.js add new todos route, or just replace ./routes/users for ./routes/todos

var todos = require('./routes/todos');
app.use('/todos', todos);

All set! Now, let’s go back and edit our routes/todos.js.

7.1 List: GET /todos

Remember mongoose query api? Here’s how to use it in this context:

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');

/* GET /todos listing. */
router.get('/', function(req, res, next) {
  Todo.find(function (err, todos) {
    if (err) return next(err);
    res.json(todos);
  });
});

module.exports = router;

Harvest time! We don’t have any task in database but at least we verify it is working:

# Start database
mongod

# Start Webserver (in other terminal tab)
npm start

# Test API (in other terminal tab)
curl localhost:3000/todos
# => []%

diff

If it returns an empty array [] you are all set. If you get errors, try going back and making sure you didn’t forget anything, or you can comment at the end of the post for help.

7.2 Create: POST /todos

Back in routes/todos.js, we are going to add the ability to create using mongoose create. Can you make it work before looking at the next example?

/* POST /todos */
router.post('/', function(req, res, next) {
  Todo.create(req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

diff

A few things:

  • HTTP methods, e.g. GET, PUT, DELETE, PATCH, POST, …
  • Base URI, e.g. [http://adrianmejia.com](http://adrianmejia.com "http://adrianmejia.com")
  • URL path, e.g. /blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
  • Media type, e.g. html, JSON, XML, Microformats, Atom, Images

Everytime you change a file you have to stop and start the web server. Let’s fix that using nodemon to refresh automatically:

# install nodemon globally
npm install nodemon -g

# Run web server with nodemon
nodemon

7.3 Show: GET /todos/:id

This is a snap with [Todo.findById](https://codequs.com/p/rytO0EuH4/creating-restful-apis-with-nodejs-and-mongodb-tutorial#mongoose-read-and-query "Todo.findById") and req.params. Notice that params matches the placeholder name we set while defining the route. :id in this case.

/* GET /todos/id */
router.get('/:id', function(req, res, next) {
  Todo.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

diff

Let’s test what we have so far!

# Start Web Server on port 4000 (default is 3000)
PORT=4000 nodemon

# Create a todo using the API
curl -XPOST http://localhost:4000/todos -d 'name=Master%20Routes&completed=false&note=soon...'
# => {"__v":0,"name":"Master Routes","completed":false,"note":"soon...","_id":"57a655997d2241695585ecf8"}%

# Get todo by ID (use the _id from the previous request, in my case "57a655997d2241695585ecf8")
curl -XGET http://localhost:4000/todos/57a655997d2241695585ecf8
{"_id":"57a655997d2241695585ecf8","name":"Master Routes","completed":false,"note":"soon...","__v":0}%

# Get all elements (notice it is an array)
curl -XGET http://localhost:4000/todos
[{"_id":"57a655997d2241695585ecf8","name":"Master Routes","completed":false,"note":"soon...","__v":0}]%

7.4 Update: PUT /todos/:id

Back in routes/todos.js, we are going to update tasks. This one you can do without looking at the example below, review findByIdAndUpdate and give it a try!

/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
  Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

diff

# Use the ID from the todo, in my case 57a655997d2241695585ecf8
curl -XPUT http://localhost:4000/todos/57a655997d2241695585ecf8 -d "note=hola"
# => {"_id":"57a655997d2241695585ecf8","name":"Master Routes","completed":true,"note":"hola","__v":0}%

7.5 Destroy: DELETE /todos/:id

Finally, the last one! Almost identical to update, use [findByIdAndRemove](https://codequs.com/p/rytO0EuH4/creating-restful-apis-with-nodejs-and-mongodb-tutorial#mongoose-delete "findByIdAndRemove").

/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
  Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

diff

Is it working? Cool, you are done then! Is NOT working? take a look at the full repository.

#node-js #mongodb #api #rest

What is GEEK

Buddha Community

Creating RESTful APIs with NodeJS and MongoDB Tutorial
Easter  Deckow

Easter Deckow

1655630160

PyTumblr: A Python Tumblr API v2 Client

PyTumblr

Installation

Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install

Usage

Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(
    '<consumer_key>',
    '<consumer_secret>',
    '<oauth_token>',
    '<oauth_secret>',
)

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
                    source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",
                    data="/Users/johnb/path/to/my/image.jpg")

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
                    embed="http://www.youtube.com/watch?v=40pUYLacrj4")

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Lets Cms

Lets Cms

1652251528

Opencart REST API extensions - V3.x | Rest API Integration, Affiliate

Opencart REST API extensions - V3.x | Rest API Integration : OpenCart APIs is fully integrated with the OpenCart REST API. This is interact with your OpenCart site by sending and receiving data as JSON (JavaScript Object Notation) objects. Using the OpenCart REST API you can register the customers and purchasing the products and it provides data access to the content of OpenCart users like which is publicly accessible via the REST API. This APIs also provide the E-commerce Mobile Apps.

Opencart REST API 
OCRESTAPI Module allows the customer purchasing product from the website it just like E-commerce APIs its also available mobile version APIs.

Opencart Rest APIs List 
Customer Registration GET APIs.
Customer Registration POST APIs.
Customer Login GET APIs.
Customer Login POST APIs.
Checkout Confirm GET APIs.
Checkout Confirm POST APIs.


If you want to know Opencart REST API Any information, you can contact us at -
Skype: jks0586,
Email: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com
Call/WhatsApp/WeChat: +91–9717478599.

Download : https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=43174&filter_search=ocrest%20api
View Documentation : https://www.letscms.com/documents/api/opencart-rest-api.html
More Information : https://www.letscms.com/blog/Rest-API-Opencart
VEDIO : https://vimeo.com/682154292  

#opencart_api_for_android #Opencart_rest_admin_api #opencart_rest_api #Rest_API_Integration #oc_rest_api #rest_api_ecommerce #rest_api_mobile #rest_api_opencart #rest_api_github #rest_api_documentation #opencart_rest_admin_api #rest_api_for_opencart_mobile_app #opencart_shopping_cart_rest_api #opencart_json_api

Lets Cms

Lets Cms

1652251629

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce

Unilevel MLM Wordpress Rest API FrontEnd | UMW Rest API Woocommerce Price USA, Philippines : Our API’s handle the Unilevel MLM woo-commerce end user all functionalities like customer login/register. You can request any type of information which is listed below, our API will provide you managed results for your all frontend needs, which will be useful for your applications like Mobile App etc.
Business to Customer REST API for Unilevel MLM Woo-Commerce will empower your Woo-commerce site with the most powerful Unilevel MLM Woo-Commerce REST API, you will be able to get and send data to your marketplace from other mobile apps or websites using HTTP Rest API request.
Our plugin is used JWT authentication for the authorization process.

REST API Unilevel MLM Woo-commerce plugin contains following APIs.
User Login Rest API
User Register Rest API
User Join Rest API
Get User info Rest API
Get Affiliate URL Rest API 
Get Downlines list Rest API
Get Bank Details Rest API
Save Bank Details Rest API
Get Genealogy JSON Rest API
Get Total Earning Rest API
Get Current Balance Rest API
Get Payout Details Rest API
Get Payout List Rest API
Get Commissions List Rest API
Withdrawal Request Rest API
Get Withdrawal List Rest API

If you want to know more information and any queries regarding Unilevel MLM Rest API Woocommerce WordPress Plugin, you can contact our experts through 
Skype: jks0586, 
Mail: letscmsdev@gmail.com,
Website: www.letscms.com, www.mlmtrees.com,
Call/WhatsApp/WeChat: +91-9717478599.  

more information : https://www.mlmtrees.com/product/unilevel-mlm-woocommerce-rest-api-addon

Visit Documentation : https://letscms.com/documents/umw_apis/umw-apis-addon-documentation.html

#Unilevel_MLM_WooCommerce_Rest_API's_Addon #umw_mlm_rest_api #rest_api_woocommerce_unilevel #rest_api_in_woocommerce #rest_api_woocommerce #rest_api_woocommerce_documentation #rest_api_woocommerce_php #api_rest_de_woocommerce #woocommerce_rest_api_in_android #woocommerce_rest_api_in_wordpress #Rest_API_Woocommerce_unilevel_mlm #wp_rest_api_woocommerce