api – Flatlogic Blog https://flatlogic.com/blog Explore and learn everything about React, Angular, Vue, Bootstrap and React Native application templates Tue, 26 Mar 2024 16:20:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 Axios Multipart Form Data- Sending File Through A Form With Javascript https://flatlogic.com/blog/axios-multipart-form-data-sending-file-through-a-form-with-javascript/ Tue, 02 Aug 2022 07:32:00 +0000 https://flatlogic.com/blog/?p=12078 Axios is an HTTP client based on a promise. It supports an easy and simple API to work and handle requests both on Node.js and browsers. Since Axios is frontend as well as backend software, it is very similar to sending a file with Axios both in Node.js and the browser. The most important job of client-side JavaScript is to make HTTP requests for fetching and saving data. And that makes Axios a very useful resource. Easy intercepting responses/requests and canceling them is another major aspect of Axios.

The post Axios Multipart Form Data- Sending File Through A Form With Javascript appeared first on Flatlogic Blog.

]]>
You are looking for a way to send files through a form using Javascript? Axios Multipart Form Data is the answer! Have you ever wondered how to include files in a form? How to send file data using Javascript, or is it even possible? How can you use Axios to send file data? With this article, you will learn all about Axios Multipart Form Data and how to send files through a form with Javascript.
The problem of sending file data through a form is a common dilemma for web developers. It is essential to know how to do this to build dynamic web applications. In research studies, such as this one, it has been proven that having a clear understanding of how to upload files is essential. Mastering Axios Multipart Form Data is a game-changer in developing business software, as it enables the seamless integration of file uploads into web applications, enhancing functionality and user interaction capabilities.

By reading this article, you will have a better understanding of Axios Multipart Form Data and how to send files through a form using Javascript. You will learn how to send files using the Axios.post() method, and how to configure your Axios request. You will also learn how to include multiple files in your form. So, if you are ready to learn more about Axios Multipart Form Data, let’s get started!

What is Axios Multipart Form Data?

Utilizing Axios Multipart Form Data is crucial for business software development, offering a streamlined approach to handling file uploads and ensuring efficient data transfer from client to server, thereby enhancing the overall functionality and user experience of web applications. Axios Multipart Form Data is a way to send files through a form using Javascript. It allows developers to include multiple files in a form, and to send them to the server using the axios.post() method. It is an efficient way to send files from the client to the server and is essential for web developers.

The Multipart Form Data encoding type can be used to include files in the form data before transferring it to the server for it to be processed. There are other types of encoding as follows-

  1. application/ x-www-form-urlencoded: The data is encoded like a string of queries. It separates the key-value pairs (denoted by ‘=’) with signs like ‘&’.
  2. text/ plain: Here, the data gets transferred just as the text itself. That means it doesn’t convert it to code for transferring. It is generally used to debug and not to produce anything.
  3. multipart/ form-data: It can include files in the form of data as stated above. Here the data is sent in the form of chunks where a character that does not appear in the content is used as a boundary symbol.
2024 Research

However, HTML Training is very beneficial to know more information on this exciting platform and enhance your career growth in this Programming & Frameworks field.

We can include any of these in our HTML form tag through the attribute- “enctype” which is optional. 

<form action = “/path/to/api” method = “POST” enctype = “ENCTYPE_HERE”></form>

It is pretty much simple to use them, and, likely, we all have already encountered it with the HTML tag- <form>. We generally omit the attribute because the default does its job alright. 

Multipart Form data and x-www-form-urlencoded

Multipart Form Data and x-www-form-urlencoded are the main two methods for sending the HTML data to the server. The complete set of data is sent as a long string of queries as far as x-www-form-urlencoded is concerned. On the other hand, Multipart Form Data uses data chunks to transfer them. Still, there are some similarities between them which are as follows-

  1. Both of them are used to send form data as POST requests.
  2. The multipart form system is mostly used for sending binary data (more specifically to upload files), while the x-www-form-urlencoded is mostly used for sending text data.
  3. Both of them are required to be supported by the user agents, such as a browser.
  4. A specific character not occurring in the entire content is used to separate each part by multipart form data. On the other hand, one big string of queries signifies all the name-value pairs as far as x-www-form-urlencoded is concerned. Here, ‘%’ replaces the reserved and alphanumeric characters. And, ‘%20’ replaces the hex value like space.
  5. The more efficient one out of these two is multipart form data. This is because a character does not need to be replaced with three bytes as the URL encoding requires.  

Differences between Fetch and Axios

AxiosFetch
The request object has a URL in Axios.The request object does not have any URL in Fetch.
There is built-in XSRF in Axios.There is no built-in XSRF in Fetch.
We can install Axios easily as it is a third-party package.The built-in package in most browsers is Fetch. Therefore there is no need to install it in most cases.
The data property is used by Axios.The body property is used by Fetch.
The ‘200’ status and ‘OK’ statusText signify that Axios is right.The OK property contained in the response object signifies that Fetch is right.
The object is contained in the data of Axios.The body of Fetch is stringified.
The transformation of JSON data is automatic in Axios.There is a process of two steps while handling the JSON data. One is for making the actual request, and the other is for calling the JSON method intentionally.
The HTTP requests can be intercepted by Axios.The HTTP requests can’t be intercepted by Fetch as per the default setting.
The requests can be canceled and timed out in Axios.The requests can’t be canceled and timed out in Axios.
Several browsers are supported by Axios.Only Firefox 39+, Chrome 42+, Safari 10.1+, and Chrome 42+ are supported by Fetch. This is called backward compatibility.
There is built-in support for download progress in Axios.The upload progress is not supported by Fetch.

Let us proceed with considering each step. From the process of sending the form data and files to Node.js (Express) using Axios to receiving it, we’ll focus on it all.

How to Install Axios?

It has become very typical now to send HTTP requests using Axios instead of fetch(). For installing Axios in the projects of Node, the following code needs to be followed. 

$ npm install Axios# OR$ yarn add Axios

A different method is also there. The files can be directly downloaded to the local machine. And then the library can be easily included as given below-

<script src = “https:// unpkg.com/ axios/ dist/ axios.min.js”></script>

How to set enctype up with HTML and Axios?

The encoding type needs to be set up for sending the multipart data form. And Axios provides several ways to achieve this. None can be considered better than the other since every one of them is equally efficient when setting up enctype.

The default global type of encoding can be set up using Axios as given below. It will make the type of encoding for all Axios requests to be of form-data type.

axios. defaults. headers. post [‘Content-Type’] = ‘multipart/form-data’;

In the second method, we can change the headers to define the kind of encoding for all separate requests. We can do this by using the following code:

Axios.post (“/path/to/api”, data, {    Headers: {        “Content- Type”: “multipart/ form-data”,    },});

The last method is probably the simplest of all. What we need to do is simply set the enctype in a particular <form> tag. The encoding type of that form will be adopted by Axios by just typing the given commands:

<form action = “/some-endpoint” method = “HTTP_METHOD” enctype = “multipart/ form data”></form>

Axios + Express

Let us build a two-input form. One is for submitting the user name and the other is for selecting a profile image:

<form action = “/Update profile” method = “post”>    <input type = “text” name = “username” placeholder = “Type the name here” />    <input type = “file” name = “userPicture” />    <button type = “submit”> submit </button></form>

If we do not use Axios, the default events will unfold. A POST request would be sent to the /update profile endpoint when we click on the “submit” button. However, an event listener can be attached to the button to override the default settings. As the requests of Axios are asynchronous, the headers can be changed and the requests can be customized.

https://www.codegrepper.com/codeimages/update-image-with-axios-form.png

Express Backend

Express JS is the cleanest as well as simplest method for spinning up a REST API. It works as a boilerplate for the server setup and to handle requests. 

Although Express is just as perfect software as possible, some middleware expansion just adds more delight to it. Therefore we can install numerous middlewares on its top for expanding its function.

The installation of Express through npm is straightforward. The express-file upload middleware can be used to handle file uploading. We can install it also easily through npm:

$ npm install Express – file upload

For starting a server and defining an endpoint to update a profile, the following steps are to be followed:

The library is imported-

Const express = require (“express”);Var file upload = require (“express-file upload”);

The app instance is created-

Const app = express();

The middleware is registered as well as set up

App.use (file upload());App.use (express.urlencoded({extended: true}));

The endpoint is requested-

App.post ( “ /update profile”, (req, res) => {  Let username = req.body.username;  Let userpicture = req.files.userPicture;  Res.send(‘    The username goes like: ${username}    The uploaded image shows like: ${userPicture.name}  ');});

And finally, the server is started.

The data that the form sends contains the request that the request handler passes. All data is contained in the setup fields like a username. The req object’s files field contains all the files. Therefore we can get them username through the req.body.username and the file that is uploaded through the req.files.user picture.

After the form is submitted through the HTML page, the API receives a request. The given output is produced in the console:

The username goes like this: The_entered_nameThe uploaded image shows like: Uploaded_name_of_file

All the information about the file kike its name, the type of encoding, and much more is returned if req.files.user picture is logged in.

Concluding Remarks

The Multipart form data has improved the efficiency of uploading data tremendously. We can upload a single object as chunks of the content. This enables us to upload any part of the content independently in the order we want. Also, the failed part can be re-transmitted without affecting the other parts of the documents. Hence, it doesn’t let the processing slow down in any way.

The post Axios Multipart Form Data- Sending File Through A Form With Javascript appeared first on Flatlogic Blog.

]]>
React Application Fetch Data [Guide] https://flatlogic.com/blog/react-fetch-data-guide/ Wed, 29 Jun 2022 15:36:00 +0000 https://flatlogic.com/blog/?p=11782 This article will guide you on how to fetch data in React with different approaches

The post React Application Fetch Data [Guide] appeared first on Flatlogic Blog.

]]>
Fetch data is a basic requirement of practically every React application. There are a variety of ways to fetch data in React, including the built-in Fetch API, Axios, async/await syntax, and others. We’ll look at some of these methods in detail.

React components can simply fetch their data. There are several options where to fetch the data:

  • Who is interested in this data? The data-fetching component should be the shared parent component for all of the components.
  • Where exactly do you want to display a load indicator (e.g. load spinner, progress indicator) when data is expected from an asynchronous request? The load indicator can be mapped to the common parent component from the first criterion. Then the common parent component will still be the data-fetching component.
    • When the loading indicator should be displayed in a higher-level component, the data fetching needs to be transferred to this component.
    • When a load indicator needs to be displayed in the child components of the common parent component, not necessarily in those components that need the data, the common parent component becomes the component to fetch the data as well. The status of the load indicator can then be transferred to all the child components that are concerned with displaying the load indicator.
  • Where is the optional error message you want to show if the request fails? The same rules from the second criterion for the load indicator apply here.

Is all about where the data should be fetched in the React component architecture. However, when data should be fetched and how should it be fetched once the generic parent component has been matched? Let’s look at some ways to retrieve data using React.

In most modern browsers, the Fetch API is a tool that is built into the window object (window. fetch) and allows to make HTTP requests very simply by using JavaScript promises.

Using a React Hooks 

Axios 

Axios is a client-side HTTP library based on promises. It facilitates sending asynchronous HTTP requests to REST endpoints and helps perform CRUD operations. That REST API/endpoint is an external API like Google API or GitHub API, or it can be your backend Node.js server. 2024 Research

This article is about a React application, so we’ll use React hooks to access states and other functions. The hooks we’ll be using are useEffect() and useState(). Essentially in this case it’ll be the useEffect() hook to fetch posts after the app renders/mounts, while the useState() hook will help create local storage for our data. First, you need to install axios by npm install axios.

  • Making GET Requests with Axios in React. GET requests are used to retrieve data from an endpoint, and this happens right after the application is rendered due to the useEffect() hook. First, it will be using a variable and then the .get() method will be connected to make a GET request to the endpoint/API. Then the .then() callback is used to get all the response data, as there is already an Axios instance that stores the base URL assigned to the variable (client).
axios get
  • Consuming GET Request. When the GET request has been successfully implemented, the next step is to consume data stored in the post-state.
  • Making POST Request with Axios in React. The POST request is used to send data to an endpoint and works similarly to a GET request, except with the function generated to perform this task, running when the form is otherwise or submitted. It will be using a .post() method. The function accepts an object to send data to and adds data to the state, removing previous data and adding new data.
axios post
  • Making DELETE Request. DELETE request is used to delete certain data from both the endpoint/API and the user interface. It will be using a .delete() method.
axios delete

Overall, Axios is about improving quality of life, not anything else. But making lots of small, step-by-step changes to the quality of life workflow can significantly improve the quality and speed of development.

async/await syntax

ECMAScript 2017 introduced the ability to use promises using async / await syntax. The advantage of this is that it allows removing .then(), .catch() and .finally() callbacks and simply getting asynchronously resolved data back as if there was writing synchronous code with no promises at all. In other words, there is no need to rely on callbacks when using async / await in React. Remember when using useEffect that the effect function cannot be made asynchronous. 

async/await

useFetch

Writing the useEffect hook with all its templates in each component you want to fetch data in is time-consuming eventually. For reducing code reuse, you can use a custom hook as a special abstraction, which you can write yourself from a third-party library (using the react-fetch-hook library). Running a custom hook on HTTP requests allows for making the components more concise. The only thing you need to do is to call the hook at the top of the component.

The load and error state should thus be able to use the same structure for this component as before when all data is returned but without useEffect. The code no longer needs to be used to resolve the promise from the GET request every time the request has to be executed.

useFetch

React-Query

The React-Query library allows handling the data implied in web service requests and maintaining applications while improving user experience. First, you need to import React, useQuery hook, and the axios libraries. Next, define an asynchronous function. And create a functional React component.

The difference between React-Query and the common data fetching library useEffect is that React-Query will return previously fetched data first and then re-fetch it again. Whereas useEffect fetches the data independently of the changed data and reloads the page.  

Conclusion

React is a great tool for building rich and high-scalable user interfaces. Some of its powerful features are the ability to fetch data and interact with it externally for a web application. There are many ways to consume the REST API in a React application, but in this guide, we’ve discussed how you can consume it using some of the most popular methods, such as Axios (a promise-based HTTP client), useEffect and useFetch hooks, React-Query Library, etc.

The post React Application Fetch Data [Guide] appeared first on Flatlogic Blog.

]]>
What is REST API? https://flatlogic.com/blog/what-is-rest-api/ Tue, 25 Jan 2022 16:28:36 +0000 https://flatlogic.com/blog/?p=9869 In this article we're discussing what is REST API, how it differs from regular APIs, and how we can use it with the highest efficiency!

The post What is REST API? appeared first on Flatlogic Blog.

]]>
  • What is REST API
  • How REST API works
  • HTTP methods
  • Best REST clients and testing tools
  • What is the REST API?

    REST, or Representational State Transfer, API  is a client-service architecture that is based on a request/response design. REST APIs are primarily used to access and work with data. 

    How the REST API works?

    The REST API works almost in the same way as any website. The call is made from the client to the server, and the data is received back via the HTTP protocol. You can also use them to provide means of accessing resources available on the server required for the client through the web browser by using request headers, request body, response body, status codes, etc.

    HTTP Methods

    HTTP methods or HTTP verbs form the main part of uniform interface constraint, followed by REST, which determines what actions have to be followed to get the requested resource. 

    GET, POST, PUT and DELETE methods can perform CRUD operations like Create, Read, Update, Delete.

    HTTP methods Get, Post, Put, and Delete can be used to perform CRUD operations: Create, Read, Update, Delete

    One of the major advantages of RESTs is that they provide lots of flexibility, allowing you to do more with that particular API. REST APIs are useful for: 2024 Research

    •  Cloud apps

    REST APIs are useful in cloud apps because their calls have no static data. If something fails, components without static data can seamlessly redeploy and scale according to load changes.

    •  Cloud services

    The REST API is also used in cloud services because you need to control how the URL is decoded to bind to the service via the API. However, cloud services and microservices are bound to make RESTful APIs the rule of the future.

    •  Web use 

    Since REST is not tied to client-side technology, you can access these APIs from a client-side web project, IoT device, or iOS App. You can build the infrastructure for your company without worrying about being tied to a specific client-side technology stack.

    Best REST Clients and Testing Tools

    1. Swagger

    Swagger is an API testing tool that allows users to start their functional, security, and performance testing right from the Open API Specifications. Some pros:

    • Supports API documentation, development, design, and testing.
    • Swagger offers many open source features for the OpenAPI specification.
    1. Postman REST Client

    With Postman, you can monitor the API, create automated tests, perform debugging, and run requests. Some pros:

    • Smooth automated testing.
    • Co-working features for easy sharing and management.
    • Supports Swagger and RAML files.
    1. Katalon Studio

    Katalon Studio provides a common place to create and perform API/Web services, UI functional, and mobile testing. Some pros:

    • Has one of the most secure assertion libraries.
    • It’s a complete package and framework.
    • Supports a data-driven approach.
    1. Karate DSL

    Karate DSL is a framework for automating API, Performance, and Load testing that has its scripting language – Domain Specific Language (DSL).  This framework runs on Java and uses the Apache HTTP client to make HTTP connections. Some pros:

    • Built-in support for JavaScript and JSON objects 
    • Very powerful JSON schema assertion and validation.
    • Parallel execution.
    • Integration with Gatling for Performance testing.

    The post What is REST API? appeared first on Flatlogic Blog.

    ]]>
    What Is API and How Does API Work? Quick introduction https://flatlogic.com/blog/what-is-api-and-how-api-works/ Fri, 21 Jan 2022 10:00:39 +0000 https://flatlogic.com/blog/?p=9793 An Application Programming Interface or API is a gateway that allows an App to communicate with other Apps and defines how that communication occurs.

    The post What Is API and How Does API Work? Quick introduction appeared first on Flatlogic Blog.

    ]]>
    What is an API

    An Application Programming Interface (API) is a gateway that allows one App to communicate with other Apps – and defines how that communication occurs. They foster connections between technologies to improve the user experience. API is a collection of software functions and procedures.


    APIs play a crucial role in business software development, facilitating secure and controlled access to resources, thereby enabling seamless integration and interaction between different services through well-defined interfaces.

    How API works

    APIs enable us to explain how web applications communicate with each other. They process data transfer between systems and locate between the application and the web server. APIs enable access to software (or web data) in a controlled and secure way for the program. Then the code sends requests to the receiving software and returns the data.

    APIs enable applications to communicate. They transfer data between systems and mediate between the application and the web server.

    APIs can be divided into four main categories based on the functionality they serve.

    APIs can be divided into four categories based on their functions. There are Open, Partner, Internal, and Composite APIs.

    APIs protocols can be divided into the next categories:

    RESTSOAPRPCSERP
    Representational state
    transfer protocol provides
    a communication channel
    to a distributed set of computers over HTTP.
    REST APIs are primarily used to access and work with data.
    Simple Object Access
    The protocol is a protocol used to transmit data over networks.
    Information is encoded using XML.
    Remote Procedural
    Callprotocol is the RPC that uses ]SON and XML.
    RPC-based APIs are primarily used for procedures or commands.
    SERP API is a web service that allows users to programmatically retrieve the search engine results page (SERP). It provides users with access to search results in JSON, RSS, or ATOM format. Integrating a tool like the SERP API can significantly enhance the capabilities of your application by providing real-time data about search engine results
    2024 Research

    Examples of APIs we use every day 

    1.    Weather snippets 

    One of the common examples of API usage is weather data like Google Search.

    Weather snippets are common examples of simple APIs

    2.    Log in using social media accounts

    The second good example of APIs usage is the log-in with Gmail/Facebook/GitHub you may have seen on different websites. Instead of logging in to users’ accounts on social networks (which would be a serious security issue), applications with this functionality use the APIs of these platforms to authenticate the user with each log-in.

    3.    Twitter Bots

    Twitter bots are accounts that automatically make tweets and send direct messages. Behind them are complex Twitter APIs. The Twitter API tells the bots when something specific happens on the platform. For example, you can ask the Twitter API to tell your bot when it gets a new repost. Here are some of the popular Twitter Bots:

    • Hundred Zeros (@HundredZeros) – Twitterbot that regularly tweets links to the eBooks that are free on Amazon.
    • Earthquake Alerts (@EarthquakeBot) ­– tweets about any earthquakes with an intensity of 5.0 or greater as they happen worldwide.
    • Free Game Findings (@freegamefinding) – the Free Game Findings bot can help you get free deals on PC/PS/Xbox games. 

    4.    Travel Booking

    Travel booking websites use third-party APIs to collect flight and hotel availabilities from providers. Here is the list of the top 5 travel booking apps:

    Which API way is the best for different software applications?

    API is a powerful tool that can help speed up your business operations, grow your brand’s reach, connect your clients to the products they want, and so much more. To further tailor these benefits to specific business needs, Custom API Integration Services play a crucial role, enabling seamless communication and data exchange between diverse systems and applications, thus enhancing operational efficiency and user experience. In the API Developer Documentation, you will find guides to the various API functions that you can use. Developers can use the Flatlogic Platform and API Generator to quickly create and manage APIs for their web applications.

    Flatlogic App Generator streamlines the API creation process by automatically generating API endpoints, API keys, and API documentation. It also includes a library of pre-built APIs that allow developers to easily integrate their applications with popular third-party services. Developers can use the API Generator to quickly and easily create and manage APIs for their applications, allowing them to deploy their web applications more quickly and provide a better user experience. Also, you can use other guides on the blog:

    The post What Is API and How Does API Work? Quick introduction appeared first on Flatlogic Blog.

    ]]>