7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (2024)

Terence Bennett - September 26, 2023

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (1)

REST Clients, or Representational State Transfer Clients, are essential tools in the world of web development and API integration. These clients facilitate seamless communication between applications and web services using the principles of REST architecture.

A REST client is a software tool, library, or framework that enables developers to interact with RESTful web services by making HTTP requests and processing responses. These clients streamline the process of connecting to APIs, allowing developers to perform CRUD (Create, Read, Update, and Delete) operations with ease, retrieve data, and manipulate it as required.

The primary reason REST clients are indispensable is their ability to abstract the low-level details of HTTP requests and responses, presenting a more user-friendly and efficient way of working with APIs. By using REST clients, developers save time and effort, allowing them to focus on core application logic and functionality.

REST clients are invaluable tools that make interacting with RESTful web services simpler and more efficient. With these clients, developers can focus on crafting exceptional applications while ensuring the seamless integration of APIs and web services.

But, what exactly is a REST client, and why is it so crucial in modern software development?

Here are the key things to know about REST clients:

  • Configuration of a sample project, such as the Address Book for JavaScript application within DreamFactory, is explained initially.
  • Guidance is provided on accessing API documentation to explore a specific endpoint, with an emphasis on checking for a successful GET request that yields a JSON representation of schema tables.
  • The article demonstrates how to make GET requests using various programming languages, including NodeJS, Python, PHP, Ruby, and Perl, offering code snippets and configuration tips.
  • Each language example highlights the importance of proper configuration to retrieve data from the API endpoint effectively.
  • Additionally, popular REST API client testing tools like Insomnia and Postman are mentioned as valuable resources for testing and interacting with APIs.

Table of Contents

Configuring the Sample Project

NodeJS REST API Example

Python REST API Example

PHP REST API Calls Example

Ruby REST API Example

Perl REST API Example

Insomnia Example

Postman Example

Even if you’re not a DreamFactory user (you should check it out, you can start a free 14-day trial of our cloud version) there’s still plenty to learn from this post!

Did you know you can generate a full-featured, documented, and secure REST API in minutes using DreamFactory? Sign up for our free 14 day hosted trial to learn how! Our guided tour will show you how to create an API using an example MySQL database provided to you as part of the trial!

Create Your No Code API Now

Configuring the Sample Project

If you’d like to follow along with these examples using live data, we suggest configuring the Address Book for JavaScript sample application. If you haven’t already installed this application within your DreamFactory instance, click on the Apps tab. On the left side of the screen click Import and Select next to the Address Book for JavaScript project. Scroll to the bottom of the screen and click the Import button. This is enough to ensure the application example data set is loaded into your DreamFactory instance, however if you want to experiment with other features you’ll also want to complete a few other configuration steps found in the aforementioned project README.

In either case, head over to API docs, choose the db service, and scroll down to the following endpoint:

GET /db/_schema

You should see the output depicted in the following screenshot:

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (2)

If the GET request executes successfully you should receive a response Code of 200 indicating success, as well as a JSON representation of the tables in your schema. Now that some sample data is available let’s experiment with a few GET requests. In our examples we will be querying the contact_info table using the following API endpoint:

GET https://localhost/api/v2/db/_table/contact_info

NodeJS REST API Example

For our first example we will look at two simple NodeJS scripts. Below is an example of a native NodeJS HTTP GET request. In your favorite text editor create a new file called rest.js and enter the following code:

const https = require("https");const options = { "method": "GET", "hostname": "example.com", "port": 443, "path": "/api/v2/db/_table/contact_info", "headers": { "x-dreamfactory-api-key": "YOUR_API_KEY", "cache-control": "no-cache" }}const req = https.request(options, function(res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function() { var body = Buffer.concat(chunks); console.log(body.toString()); });});req.end()

After updating the hostname and x-dreamfactory-api-key fields to reflect the location and assigned application API key associated with your DreamFactory instance, save the changes and run the script via your terminal:

$ node rest.js

A large block of JSON data should be returned. If you’d like to clean it up and look a little more closely at your data you can copy the response and paste it into JSONLint. After pasting the data into the text area, click Validate JSON. This will accomplish two important tasks:

  1. Format your JSON into something a little more human readable.
  2. Validate that the JSON is in correct format as described by the JSON spec. If for any reason the JSON isn’t valid you will be given a hint as to what steps to take to correctly format your JSON.

That script felt a little heavy handed for just one simple GET call. Let’s try the same call again but this time we will use the ‘unirest’ module. NPM comes with NodeJS and allows users to install what are called Node modules. If you plan on doing any custom scripted services or events scripting in your DreamFactory this will also be useful. Let’s install the ‘unirest’ module using NPM, open up a shell and type:

$ npm install -g unirest

The -g option installs the module globally. We recommend installing NodeJS modules globally, especially if you intend to use them in your server-side scripts. Now that you’ve installed the unirest module open up your text editor and paste in the following code:

var unirest = require("unirest")var req = unirest("GET", "https://example.com/api/v2/db/_table/contact_info")req.headers({ "cache-control": "no-cache", "x-dreamfactory-api-key": "YOUR_API_KEY"})req.end(function (res) { if (res.error) throw new Error(res.error) console.log(res.body)})

Save the script as resty.js and run it like so:

$ node resty.js

As with before, you’ll receive a lengthy JSON response in return. However this time it was accomplished with a lot less code with the added bonus of formatted JSON!

Python REST API Example

Maybe NodeJS isn’t your cup of tea, and instead prefer Python. Python makes REST a cakewalk with the requests module. Let’s install the requests module using pip,the Python package manager. Open up your terminal and execute:

$ pip install requests

Now that the requests module is installed let’s again open up a text editor and enter the following code:

import requestsurl = "https://example.com/api/v2/db/_table/contact_info?limit=5"headers = { "cache-control": "no-cache", "x-dreamfactory-api-key": "YOUR_API_KEY"}response = requests.request("GET", url, headers=headers)print(response.text)

Once you’ve confirmed everything is correct save the file as rest.py and again navigate to the directory where you saved your script and enter:

$ python rest.py{"resource":[{"id":1,"ordinal":0,"contact_id":1,"info_type":"home","phone":"500 555-0162","email":"[emailprotected]","address":"3761 N. 14th St","city":"MEDINA","state":"ND","zip":"58467","country":"USA"},{"id":2,"ordinal":0,"contact_id":1,"info_type":"work","phone":"500 555-0110","email":"[emailprotected]","address":"2243 W St.","city":"MEDINA","state":"ND","zip":"58467","country":"USA"},...]}

As with the other examples, if everything is configured properly you’ll see the JSON returned in the script output.

The DreamFactory platform also supports using Python (versions 2 and 3) to add business logic to existing API endpoints, and create new standalone APIs. You can learn more about DreamFactory’s scripting abilities in the Getting Started with DreamFactory guide.

PHP REST API Example

Still other readers may wish to send HTTP API requests using PHP. No problem! Return to your editor and enter the following code:

<?php$curl = curl_init();curl_setopt_array($curl, [ CURLOPT_URL => "https://example.com/api/v2/db/_table/contact_info?limit=5", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET"]);curl_setopt($curl, CURLOPT_HTTPHEADER, [ "cache-control: no-cache", "X-DreamFactory-API-Key: YOUR_API_KEY"]);$response = curl_exec($curl);$error = curl_error($curl);curl_close($curl);if ($error) { echo "cURL error #:" . $error;} else { echo $response;}

Save the file as rest.php and run the script like so:

$ php rest.php

You can learn more about DreamFactory’s scripting abilities in the Getting Started with DreamFactory guide.

Ruby REST API Example

Ruby has more HTTP client libraries then I can count on my fingers and toes. In this section we will cover two. Let’s first make a call using net/http which is built into the Ruby standard library. Open your text editor and paste in the following code:

require 'uri'require 'net/http'url = URI('https://example.com/api/v2/db/_table/contact_info?limit=5')http = Net::HTTP.new(url.host, url.port)http.use_ssl = truerequest = Net::HTTP::Get.new(url)request['X-DreamFactory-API-Key'] = 'YOUR_API_KEY'request['cache-control'] = 'no-cache'response = http.request(request)puts response.read_body

Save these changes and execute the script like so:

$ ruby rest.rb

Now let’s try this again, however this time we are going to use the Ruby httparty gem. This incredibly useful Ruby gem which claims to “make http fun again” can be used interactively in the command line or within your Ruby, Sinatra and Ruby on Rails applications. Lets use Ruby’s package manager to install the httparty gem:

$ gem install httparty

Once you’ve installed the httparty gem open up your editor and paste the following code into a file called rest2.rb:

require 'httparty'require 'json'url = 'https://example.com/api/v2/db/_table/contact_info?limit=5'headers = { "X-DreamFactory-API-Key" => "YOUR_API_KEY", "cache-control" => "no-cache"}response = HTTParty.get(url, :headers => headers)json = JSON.parse(response.body)puts response.bodyputs response.message.to_json

Save the file and execute it like so:

$ ruby rest2.rb

Perl REST API Example

Let’s move onto a Perl example. Begin by using Perl’s CPAN package manager to install the REST::Client Perl module. Open up your terminal and enter the following command:

$ cpan

Once in the cpan shell execute this command:

install REST::Client

After REST::Client finishes installing exit the cpan shell, open your editor, and paste in the following code:

use REST::Client;my $client = REST::Client->new();$client->getUseragent()->ssl_opts(verify_hostname => 0);$client->getUseragent()->ssl_opts(SSL_verify_mode => SSL_VERIFY_NONE);$client->addHeader('X-DreamFactory-API-Key', 'YOUR_API_KEY');$client->addHeader('cache-control', 'no-cache');$client->GET("https://example.com/api/v2/db/_table/contact_info?limit=56");print $client->responseContent();

Save the file and run it using the following command:

$ perl rest.pl

REST API Client Testing Tools

Insomnia

Insomnia is a great API testing tool that the DreamFactory team uses every day to demonstrate various platform features. It’s freely available for download via the Insomnia website, and a paid version (which we use) allows teams to share API call libraries. It’s very easy to use as the following screenshot indicates. You’ll identify the request method (GET, POST, etc), the desired URL, and pass along the API key. With the call configured, just press the Send button and the request results will appear in the right hand panel.

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (3)

Postman

Like Insomnia, Postman is a very popular API testing tool, with a considerable number of additional features useful for API development. It’s interface isn’t as streamlined as Insomnia, but is nonetheless easy to use as the following screenshot indicates. You’ll identify the request method, set the URL and any headers, and press Send. The results will be output in the bottom pane.

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (4)

Did you know you can generate a full-featured, documented, and secure REST API in minutes using DreamFactory? Sign up for our free 14 day hosted trial to learn how! Our guided tour will show you how to create an API using an example MySQL database provided to you as part of the trial!

Create Your No Code API Now

Conclusion

Boom! So there you have it, 7 quick and easy examples to obtain and parse data from the DreamFactory REST API. Something else you may have noticed is that the API endpoint was used over and over again in each of the client calls without requiring a single line of server-side code, awesome!

Frequently Asked Questions (FAQ) for “7 Simple REST Client Examples for Retrieving API Data”

1. What is a REST client?

A REST (Representational State Transfer) client is a tool or library used for making HTTP requests and interacting with RESTful web services. These clients allow developers to easily perform CRUD (Create, Read, Update, and Delete) operations, retrieve API data, and manipulate it as required.

2. Why is it important to use a REST client when working with APIs?

Using a REST client makes it easier to interact with APIs by abstracting away the low-level details of HTTP requests and responses. They provide a more efficient and user-friendly way to test, debug, and integrate APIs into applications, saving time and effort for developers.

3. What are some popular REST client tools and libraries?

Some popular REST client tools and libraries include:

  • Postman: A comprehensive API testing and development tool with a user-friendly interface.
  • Insomnia: A powerful REST client with a modern interface for API debugging and testing.
  • cURL: A versatile command-line tool for making HTTP requests.
  • axios: A popular promise-based JavaScript library for making HTTP requests in Node.js and browser environments.
  • fetch: A built-in JavaScript API for making HTTP requests in modern web browsers.
  • requests: A widely-used Python library for making HTTP requests.
  • RestClient: A Ruby gem for making RESTful API requests.

4. How do I use a REST client to retrieve API data?

To retrieve API data using a REST client, follow these steps:

  1. Choose a REST client tool or library suitable for your project’s requirements and language.
  2. Set the HTTP method (usually GET for retrieving data) and provide the API endpoint URL.
  3. Configure any required headers, such as API keys or authentication tokens.
  4. Send the request and receive the API response.
  5. Parse and manipulate the returned data as needed.

5. Are REST clients only used for retrieving data from APIs?

No, REST clients can be used for various CRUD operations, including creating, updating, and deleting data. Depending on the HTTP method used (POST, PUT, PATCH, or DELETE), a REST client can perform different actions on API resources.

6. Can I use a REST client for APIs that are not RESTful?

While REST clients are primarily designed for interacting with RESTful APIs, some clients like Postman and Insomnia can also be used to test and debug non-RESTful APIs, such as GraphQL or SOAP-based web services.

7. How can I ensure my REST client code is secure and efficient?

To ensure your REST client code is secure and efficient:

  • Use HTTPS for all API requests to encrypt data in transit.
  • Validate and sanitize user input to prevent security vulnerabilities like SQL injection or cross-site scripting (XSS).
  • Use proper authentication and authorization methods, such as API keys or OAuth 2.0.
  • Implement error handling and retry mechanisms for failed requests.
  • Optimize the number of API calls by caching data and using pagination or filtering when possible.

Sign up for a 14-day free trialand start creating your APIs today!

Related Reading:

REST APIs vs Microservices: Key Differences

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (5)

Terence Bennett

Terence Bennett, CEO of DreamFactory, has a wealth of experience in government IT systems and Google Cloud. His impressive background includes being a former U.S. Navy Intelligence Officer and a former member of Google’s Red Team. Prior to becoming CEO, he served as COO at DreamFactory Software.

7 Simple REST Client Examples for Retrieving API Data | Dreamfactory (2024)

FAQs

How to retrieve data from REST API? ›

To retrieve API data using a REST client, follow these steps:
  1. Choose a REST client tool or library suitable for your project's requirements and language.
  2. Set the HTTP method (usually GET for retrieving data) and provide the API endpoint URL.
  3. Configure any required headers, such as API keys or authentication tokens.

What is a good example of a REST API? ›

Social media sites like Twitter, Facebook use REST APIs to integrate with third-party applications and allow posting updates. Ridesharing apps like Uber and Lyft use REST APIs to coordinate cars, obtain maps, fares and location data.

How to call API using REST client? ›

Calling REST APIs
  1. Add a Datasource with OpenAPI specification. Datasource for REST service without OpenAPI specification.
  2. Add a service. Define the methods that map to the operations.
  3. Add a Controller. Inject the Service in the constructor. Add the REST endpoints.
  4. More examples.
  5. Further reading.

How do I pull data from an API? ›

How to use data extraction API?
  1. Step 1 - Kickstart your journey by signing up! ...
  2. Step 2 - Go through API documentation. ...
  3. Step 3 - Set up the platform. ...
  4. Step 4 - Send an API request. ...
  5. Step 5 - API authentication. ...
  6. Step 6 - Parameterizing requests. ...
  7. Step 7 - Errors handling. ...
  8. Step 8 - Extraction and integration.

How to retrieve json from REST API? ›

To get JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.

What are the 4 most common REST API operations? ›

An API is a set of rules and specifications that software programs can follow to communicate with each other. The four most common REST API operations are create, read, update, and delete (CRUD).

What is the best example of REST? ›

Running, cycling, jumping, swimming, eating, drinking, playing, writing, typing, moving cars, and throwing a ball are all examples of motion. Sleeping, sitting, standing, lying, a fixed clock, a bottle on a table, and a stopped car are all examples of rest.

What is REST API for beginners? ›

What Is a REST API? A REST API is a standardized approach to building APIs that entails using the representational state transfer (REST) architectural style to communicate with servers.

What are the different types of REST clients? ›

RestClient - synchronous client with a fluent API. WebClient - non-blocking, reactive client with fluent API. RestTemplate - synchronous client with template method API. HTTP Interface - annotated interface with generated, dynamic proxy implementation.

How to communicate with REST API? ›

All communication done via REST API uses only HTTP request. Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST or PUT or DELETE request. After that, a response comes back from the server in the form of a resource which can be anything like HTML, XML, Image, or JSON.

What is an API call example? ›

Suppose someone searches for bus tickets on a travel website. The travel website sends an API call to the various bus companies' servers and receives back information about what rides are available and how much they cost. From the user's perspective, this process should be almost instantaneous.

What is a daily example of an API? ›

Public API examples include social media bots, third-party login, e-commerce transactions, and weather apps. Private API examples include streaming services, ensuring media compatibility on various devices, and financial apps that connect different aspects of managing finances in a bank.

What are API examples? ›

APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. For example, the weather bureau's software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone.

How do I download data from REST API? ›

So stepwise:
  1. Make the REST request and save the response to a filedocument.
  2. Retrieve via association the latestHTTPResponse/httpHeaders List.
  3. Filter the list for the filename header (if it exists)
  4. Update the name of the filedocument object with the content of the header.
  5. Download file.
Mar 26, 2021

How do I get responses from REST API? ›

rest-api-response-format
  1. GET - Get single item - HTTP Response Code: 200. ...
  2. GET - Get item list - HTTP Response Code: 200. ...
  3. POST - Create a new item - HTTP Response Code: 201. ...
  4. PUT - Update an item - HTTP Response Code: 200/204. ...
  5. DELETE - Delete an item - HTTP Response Code: 204.

How to import data from REST API? ›

Import Data Using REST APIs
  1. Identify the Objects to Import Your Data.
  2. Get Object MetaData.
  3. Select Required Object Attributes.
  4. Download the Import Template for the Object.
  5. Create Import Map.
  6. Create Mapping Columns.
  7. Upload the Source File to Oracle UCM.
  8. Enable Survivorship (Optional)

How do I get data from REST API in Excel? ›

Power Query is a data transformation engine within Excel. As well, it allows you to query data from different sources including REST APIs. Here is what you need to do to link API to Excel. In your Excel workbook, go to Data => New Query => From Other Sources => From Web.

Top Articles
10 Easy Jobs that Pay Well | FlexJobs
Credit Cards with $20,000 Limit Guaranteed Approval
Design215 Word Pattern Finder
Dte Outage Map Woodhaven
Mrh Forum
Tesla Supercharger La Crosse Photos
Nation Hearing Near Me
Noaa Weather Philadelphia
Overzicht reviews voor 2Cheap.nl
Back to basics: Understanding the carburetor and fixing it yourself - Hagerty Media
Western Razor David Angelo Net Worth
Snarky Tea Net Worth 2022
Aries Auhsd
Craigslist Free Grand Rapids
R/Altfeet
Hmr Properties
Viha Email Login
Arboristsite Forum Chainsaw
Conan Exiles Colored Crystal
Dtab Customs
Tygodnik Polityka - Polityka.pl
Jbf Wichita Falls
Wausau Marketplace
Weepinbell Gen 3 Learnset
Outlet For The Thames Crossword
Wisconsin Volleyball Team Boobs Uncensored
55Th And Kedzie Elite Staffing
Kimoriiii Fansly
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Rays Salary Cap
What Is Opm1 Treas 310 Deposit
Verizon TV and Internet Packages
Leland Nc Craigslist
Tamilyogi Ponniyin Selvan
Vip Lounge Odu
10 Most Ridiculously Expensive Haircuts Of All Time in 2024 - Financesonline.com
Metra Schedule Ravinia To Chicago
Dying Light Nexus
Main Street Station Coshocton Menu
Invalleerkracht [Gratis] voorbeelden van sollicitatiebrieven & expert tips
Lake Andes Buy Sell Trade
Craigslist Odessa Midland Texas
Homeloanserv Account Login
Watch Chainsaw Man English Sub/Dub online Free on HiAnime.to
White County
Keci News
DL381 Delta Air Lines Estado de vuelo Hoy y Historial 2024 | Trip.com
bot .com Project by super soph
Mail2World Sign Up
Phumikhmer 2022
Unity Webgl Extreme Race
Varsity Competition Results 2022
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6493

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.