Wednesday, February 5, 2020

An Introduction to REST and RESTful APIs

An Introduction to REST and RESTful APIs

REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.

Sharing data between two or more systems has always been a fundamental requirement of software development. For example, consider buying motor insurance. Your insurer must obtain information about you and your vehicle so they request data from car registration authorities, credit agencies, banks, and other systems. All this happens transparently in real time to determine whether a policy can be offered.

REST Example

Open the following link in your browser to request a random programming joke:

https://official-joke-api.appspot.com/jokes/programming/random

This is a public API implemented as RESTful web service (it follows REST conventions). Your browser will show an awful JSON-formatted programming joke, such as:

[
  {
    "id": 29,
    "type": "programming",
    "setup": "There are 10 types of people in this world...",
    "punchline": "Those who understand binary and those who don't"
  }
]

You could request the same URL and get a response using any HTTP client, such as curl:

curl "https://official-joke-api.appspot.com/jokes/programming/random"

HTTP client libraries are available in all popular languages and runtimes including Fetch in JavaScript and file_get_contents() in PHP. A JSON response is machine-readable so it can be parsed and output in HTML or any other format.

REST and the Rest

Various data communication standards have evolved over the years. You may have encountered standards including CORBA, SOAP, or XML-RPC, which usually established strict messaging rules.

REST was defined in 2000 by Roy Fielding and is considerably simpler. It's not a standard but a set of recommendations and constraints for RESTful web services. These include:

  1. Client-Server. SystemA makes an HTTP request to a URL hosted by SystemB, which returns a response.

    It's identical to how a browser works. The application makes a request for a specific URL. The request is routed to a web server that returns an HTML page. That page may contain references to images, style sheets, and JavaScript, which incur further requests and responses.

  2. Stateless. REST is stateless: the client request should contain all the information necessary to respond to a request. In other words, it should be possible to make two or more HTTP requests in any order and the same responses will be received.

  3. Cacheable. A response should be defined as cacheable or not.

  4. Layered. The requesting client need not know whether it’s communicating with the actual server, a proxy, or any other intermediary.

Creating a RESTful Web Service

A RESTful web service request contains:

  1. An Endpoint URL. An application implementing a RESTful API will define one or more URL endpoints with a domain, port, path, and/or querystring — for example, https://mydomain/user/123?format=json.

  2. The HTTP method. Differing HTTP methods can be used on any endpoint which map to application create, read, update, and delete (CRUD) operations:

    HTTP method CRUD Action
    GET read returns requested data
    POST create creates a new record
    PUT or PATCH update updates an existing record
    DELETE delete deletes an existing record

    Examples:

    • a GET request to /user/ returns a list of registered users on a system
    • a POST request to /user/123 creates a user with the ID 123 using the body data
    • a PUT request to /user/123 updates user 123 with the body data
    • a GET request to /user/123 returns the details of user 123
    • a DELETE request to /user/123 deletes user 123
  3. HTTP headers. Information such as authentication tokens or cookies can be contained in the HTTP request header.

  4. Body Data. Data is normally transmitted in the HTTP body in an identical way to HTML <form> submissions or by sending a single JSON-encoded data string.

The Response

The response payload can be whatever is practical: data, HTML, an image, an audio file, and so on. Data responses are typically JSON-encoded, but XML, CSV, simple strings, or any other format can be used. You could allow the return format to be specified in the request — for example, /user/123?format=json or /user/123?format=xml.

An appropriate HTTP status code should also be set in the response header. 200 OK is most often used for successful requests, although 201 Created may also be returned when a record is created. Errors should return an appropriate code such as 400 Bad Request, 404 Not Found, 401 Unauthorized, and so on.

Other HTTP headers can be set including the Cache-Control or Expires directives to specify how long a response can be cached before it’s considered stale.

However, there are no strict rules. Endpoint URLs, HTTP methods, body data, and response types can be implemented as you like. For example, POST, PUT, and PATCH are often used interchangeably so any will create or update a record.

REST "Hello World" Example

The following code creates a RESTful web service using the Node.js Express framework. A single /hello/ endpoint responds to GET requests.

Ensure you have Node.js installed, then create a new folder named restapi. Create a new package.json file within that folder with the following content:

{
  "name": "restapi",
  "version": "1.0.0",
  "description": "REST test",
  "scripts": {
    "start": "node ./index.js"
  },
  "dependencies": {
    "express": "4.17.1"
  }
}

Run npm install from the command line to fetch the dependencies, then create an index.js file with the following code:

// simple Express.js RESTful API
'use strict';

// initialize
const
  port = 8888,
  express = require('express'),
  app = express();

// /hello/ GET request
app.get('/hello/:name?', (req, res) =>
  res.json(
    { message: `Hello ${req.params.name || 'world'}!` }
  )
);

// start server
app.listen(port, () =>
  console.log(`Server started on port ${port}`);
);

Launch the application from the command line using npm start and open http://localhost:8888/hello/ in a browser. The following JSON is displayed in response to the GET request:

{
  "message": "Hello world!"
}

The API also allows a custom name, so http://localhost:8888/hello/everyone/ returns:

{
  "message": "Hello everyone!"
}

The post An Introduction to REST and RESTful APIs appeared first on SitePoint.


by Craig Buckler via SitePoint

Facebook Welcomes Dropbox CEO, Drew Houston to the Board

Recently, Susan Desmond-Hellman left Facebook’s Board and to fill the spot, Zuckerberg’s pal Houston has put his foot down. Facebook’s shareholders have repeatedly requested the board to remove Zuckerberg as the Chairman of the company, but the board has never paid heed to the investors’...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Madiha via Digital Information World

Smartphone Users Spend a Majority of Time With Social Media and Communication Apps

By this point in time the smartphone has become a thoroughly ingrained part of our day to day lives, but this doesn’t mean that we all use our devices for the same purpose. Some people prefer to use their phones for gaming, with video and entertainment serving as another major reason of smartphone...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

What's the carbon footprint of your website?

#426 — February 5, 2020

Read on the Web

Frontend Focus

CO2 Emissions On The Web — Sites are said to now be four times bigger than they were in 2010. This post looks at the energy costs of data transfer and what you can do to reduce your web carbon footprint.

Danny van Kooten

Old CSS, New CSS — This is a tale of one individuals personal history with CSS and web design, offering a comprehensive, detailed “blend of memory and research”. A great trip down memory lane for any of you who got started on the web in the 90s.

Evelyn Woods

Open-Source Serverless CMS Powered by React, Node & GraphQL — The way we build, deploy and operate the web is evolving. Webiny is a developer-friendly serverless CMS. Use it to build websites, APIs and apps and deploy them as microservices. SEO-friendly pages and fast performance. View on GitHub.

Webiny sponsor

How Smashing Magazine Manages Content: Migration From WordPress To JAMStack — An interesting look at how a big site like Smashing Magazine went about migrating from WordPress to a static infrastructure. This technical case study covers the gains and losses, things the Smashing team had wished they’d known earlier, and what they were surprised by.

Sarah Drasner

▶  What’s New in DevTools in Chrome 80 — New features include improved WebAssembly debugging, network panel updates, support for let and class redeclarations and more.

Google Chrome Developers

A New Technique for Making Responsive, JavaScript-Free Charts — There are countless libraries for generating charts on the web, but they all seem to require JavaScript. Here’s how the New York Times approached JS-free charts with SVG.

Rich Harris

Bringing The Microsoft Edge DevTools to More Languages

Erica Draud (Microsoft)

💻 Jobs

Frontend Developer at X-Team (Remote) — Work with the world's leading brands, from anywhere. Travel the world while being part of the most energizing community of developers.

X-Team

Find a Dev Job Through Vettery — Vettery is completely free for job seekers. Make a profile, name your salary, and connect with hiring managers from top employers.

Vettery

📙 News, Tutorials & Opinion

HTML Attributes to Improve Your Users' Two Factor Authentication Experience — How to use the HTML autocomplete, inputmode and pattern attributes to improve the user experience of logging in.

Phil Nash

▶  Exploring the Frontend Performance of the UK's National Rail Website — Runs through using the layers panel in Chrome DevTools to diagnose performance issues on a high traffic website.

Umar Hansa

Transitioning Hidden Elements — Paul Hebert has written a little JavaScript utility to wrap up all of the intricacies of dealing with transitioning hidden elements - often tricky as they’re not in the document flow.

Cloud Four

How I Recreated A Polaroid Camera with CSS Gradients Only — A high-level tutorial showing how to recreate physical products with just CSS. The end result here is a Polaroid camera made entirely out of gradients.

Sarah L. Fossheim

The React Hooks Guide: In-Depth Tutorial with Examples. Start Learning — Learn all about React Hooks as we comprehensively cover: State and Effects, Context, Reducers, and Custom React Hooks.

Progress KendoReact sponsor

How To Create A Headless WordPress Site On The JAMstack

Sarah Drasner & Geoff Graham

Using the CSS line-height Property to Improve Readability

William Le

Possibly The Easiest Way to Run a Static Site Generator

CSS Tricks

Getting Keyboard-focusable Elements — A quick JavaScript function for managing focus.

Zell Liew

Shopping for Speed On eBay — This case study explains how eBay increased key metrics by optimizing the performance of their web/app experiences.

Addy Osmani

How We Started Treating Frontend Performance as a Feature — A non-technical guide to the decisions HubSpot made (and the tools they now utilise) that helped them start treating frontend performance as a feature.

Adam Markon

🔧 Code, Tools and Resources

LegraJS — Lego Brick Graphics — A small (3.36KB gzipped) JS library that lets you draw using LEGO like brick shapes on an HTML <canvas> element.

Preet Shihn

massCode: A Free and Open Source Code Snippets Manager

Anton Reshetov

Axe Pro: Free Accessibility Testing Tool Created for Development Teams

Deque sponsor

micro-jaymock: Tiny API Mocking Microservice for Generating Fake JSON Data

Meeshkan

Craft 3.4 is Here — Version 3.4 of this paid CMS brings improvements to user experience, collaboration, GraphQL, and more.

Craft

   ðŸ—“ Upcoming Events

Flashback Conference, February 10-11 — Orlando, USA — Looks at cutting-edge web dev, browser APIs and tooling, but adds how they’ve evolved from the past to the web of today.

Frontend Developer Love, February 19-21 — Amsterdam, Netherlands — Three full days of talks from 35+ global JavaScript leaders from around the world.

ConveyUX, March 3-5 — Seattle, USA — This West Coast user experience conference features over 65 sessions across three days.

W3C Workshop on Web & Machine Learning, 24-25 March — Berlin, Germany — Hosted by Microsoft, this free event aims to “bring together providers of Machine Learning tools and frameworks with Web platform practitioners to enrich the Open Web Platform with better foundations for machine learning”.


by via Frontend Focus

Changes Come to Facebook Messenger Kids Following Security Concerns

When Facebook came out with Messenger Kids, the general reaction to the development was rather mixed. A big part of the reason why this is the case has to do with the fact that Facebook has often tried to acquire data from children using decidedly underhanded methods such as when an app associated...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zia Muhammad via Digital Information World

Maintaining Perfect Feed Is Taking Tool On Social Media Influences

The influencer industry is becoming a giant in the branding and marketing business. Who would have thought that making small videos on YouTube can land someone as the ambassador of the biggest makeup brand or a sport franchise? At a timid age of just 3, there are toy reviewers earning millions...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Aabroo Saeed via Digital Information World

How to Create a Facebook Marketing Plan That Models Your Customer Journey

Is your Facebook marketing meeting your customers where they are? Wondering how to design a Facebook plan that supports your sales funnel? In this article, you’ll discover how to create a customer-centric Facebook marketing plan that meets your prospects and customers at every stage of their customer journeys. #1: Map Out Multiple Customer Journey Scenarios […]

The post How to Create a Facebook Marketing Plan That Models Your Customer Journey appeared first on Social Media Marketing | Social Media Examiner.


by Jessica Campos via Social Media Marketing | Social Media Examiner