Header image

Explore all articles in Others

Differences in UX demands of a desktop and mobile app for a SaaS product (1)

Others

Tech Stack

+0

    Differences In UX Demands Of A Desktop And Mobile App For A SaaS Product

    While it was more common for individuals and institutions to buy software in the earlier days, the concept of software as a service isn’t that new either. And as smartphones get smarter and more accessible, many product companies are shifting their focus to this ballooning market to sustain and increase profit. But even though many have increased revenue by enhancing their mobile apps, some companies are excelling thanks to a good desktop app UX. Mobile apps often shine when it comes to daily life products for the individual end user while desktop apps encapsulate stunning collaboration and productivity solutions. A recent StatCounter study put desktop traffic at 56.51%, with mobile traffic at 50.48%. Many other reports show that there’s still a roughly 60-40 split in mobile and desktop traffic. Both market segments are here to stay, so let’s examine the differences between UX design for desktop and UX design for mobile: UI Details One of the significant differences is that desktop users are more comfortable having plenty of items fixed on a single UI screen/window. In contrast, mobile users have limited screen space and may use their thumbs more than any other finger, so you can hardly get away with a cluttered UI. Not only does it look overwhelming, but it also increases the chances of a user tapping the wrong button/option. Unfortunately, there are no straightforward solutions to this challenge. You're likely to tuck a feature/function two or more screens away, which users won't be so happy about. Luckily, some designs enable you to have retractable menus that slide into place and then slide away. You also have the option to create circular icon menus that appear when you hold down a button for a while. Ultimately, you should have a navigation option that makes it easy to go to the previous page or return to the general menu. Source: Freepik You’ll also need to include a button for the most important action a user can take at that stage in their journey. If it's the opening page, this could be a signup button; if it's a category page, it could be an "add to cart" button or a "buy" button if it's the checkout page. Whatever the CTA is, it should be visible. The user shouldn't have to first scroll down the page. It should also be within the thumb zone, so ensure it's wide enough. UX design for mobile should also consider the unique gestures like swiping, tilting and shaking that can make a mobile app more fun to use, not forgetting the use of haptic feedback to respond to a user’s command. >>> Explore more articles about UI and UX design: Top 10 Design Tools For UX And UI (2025 GUIDE)Top Emerging Trends In App UI Design (2025 OUTLOOK)Atomic Design In Software Development Performance Ideally, both desktop and mobile app versions should be as smooth and fast as possible. However, when you consider the context in which they operate and the behind-the-scenes work involved in making apps faster, you realize that you might need to put more emphasis on one of them. Mobile apps are more likely to be run on devices with limited RAM, storage space and processing power. Additionally, users are more likely to travel with mobile devices to remote areas where internet connectivity may be poorer. This is why it is essential to optimize mobile apps so they can still work fine when low on resources. From memory allocation to caching, reliance on CDNs and compression for lighter media file versions, offline modes, variable streaming bitrates and data template reuse, there are various techniques you can use to achieve higher mobile app performance. Additionally, don’t forget to test on as many devices and OS versions as possible. Personalization Many software users want to feel like the product was made just for them and it deeply understands them. In the past, personalization came in the form of changeable skins, fonts and colors. Later, it advanced to more important features like changing languages, currencies and measurement systems. However, personalization has to evolve even further. For instance, if the user has enabled your mobile app to access their location, can it suggest the perfect playlist when it detects that they are by the beach or at a riverside campsite or safari lodge. Can your shopping app switch to suggestions for sweaters and cold-weather clothes when the user is in a cold region? Will your food app point them to the places with the best hot beverages and confectioneries? Personalization covers several areas, including the way a person types and uses emojis, the order in which they browse pages, how they use search bars and more. Unlike desktop apps that run on devices like work computers that stay in the same place and are shared, or laptops that usually move between work and home, a mobile app often runs on a device that spends most of its time with one person, going everywhere. This is why making mobile app versions as adaptable to the user as possible is crucial. Security and Customer Support On the security front, mobility creates more headaches since it increases the chances of a user losing a device or connecting to an unsecured public network, among other scenarios. This means you should augment mobile apps with more security options, such as fingerprint locks, face ID and other approaches that a mobile device's native hardware can allow. On a deeper level, developers can look into code obfuscation, "root," and "jailbreak detection " to further protect against attack techniques that take advantage of the mobile app-specific architectural and operational characteristics. When it comes to customer support, mobile app UX designers can look into things like the ability to screenshot an error message page and quickly submit it via live chat or tap a call button to speak to an agent. Another vital customer support area is self-help. Remember, desktop app versions have the advantage since there's more space to display a help article column alongside the actual screen/dashboard where the user is working. They can also properly display video demos and offer an Info view where you see what a button or other element does by hovering the cursor over it. That said, mobile app UX designers need to find ways to condense knowledge bases and other self-help materials within the app to simplify the journey from learning to applying. They can also use GIFs to strike a middle-ground between heavy videos and static images when delivering demos. Wrapping Up Overall, it's prudent not to consider the desktop outdated. Instead, focus more on what it easily accommodates, then figure out how to emulate that on mobile devices. As always, it helps to work with a team of professionals conversant with the nuances of developing and delivering desktop and mobile SaaS apps. You can start this journey by contacting the SupremeTech team for a free consultation on how we bring software ideas to life for our clients.

    25/11/2022

    2.29k

    Others

    +1

    • Tech Stack

    Differences In UX Demands Of A Desktop And Mobile App For A SaaS Product

    25/11/2022

    2.29k

    How Agile development influences developer and QA tool choices

    +0

      How Agile Development Influences Developer And QA Tool Choices

      On the surface, it might seem like the Agile methodology is simply about reimagining waterfall development by keeping an open mind. However, this approach has far-reaching implications for people, tools and processes. That said, let’s dissect the major Agile development characteristics that affect developer and quality assurance (QA) tool choices and talk about some great examples of Agile development tools: Increased Collaboration Agile development pushes for greater synergy amongst teams. It's hard to release higher-quality products faster if many of the people involved aren't openly communicating with each other about challenges. For example, a developer working alone can easily store, manage and reuse code using one machine. However, things get trickier once a project needs more hands and numerous software units are being created. You'll need a space where everyone's work can be converged, with changes indicated coherently. Photo by Tim van der Kuip on Unsplash  This is where tools like GitHub come in. GitHub will enable developers to combine their code into modules and easily perform version control. More importantly, developers can do all this remotely since it's cloud-based. It’s also worth noting that GitHub isn’t the only code hosting/management solution out there. You can always try others like TaraVault, AWS CodeCommit, Bitbucket, SourceForge, and many more. By the way, collaboration doesn’t begin only when the team has been formed. It’s an ethos that can be applied even when building the team and responding to talent departure or unavailability. With tools like Crowdsource.io, you can set up a project folder, post your needs and respond to interested developers. This social approach simplifies recruitment, especially during emergencies. Continuous Testing In continuous testing, teams don’t have to wait for all units to be ready before they start. Instead, they endeavor to test whatever small piece is ready as others are prepared. By doing so, they are less likely to be blindsided by complex problems in the software that delay a release as the team tries to fix them. This approach often means the testing workload will fluctuate as the project progresses, so quality assurance teams will have to be swifter at scaling testing capacity accordingly. One of the best ways to achieve this is by using test automation tools. Photo by freestocks on Unsplash More specifically, you'll need user-friendly test automation tools if teams are to quickly add new automations in response to changes in the testing workload. They should also facilitate reusability and easily plug into your CI/CD pipelines, which is what tools like Leapwork are good at. Additionally, an Agile testing team needs robust tracking and reporting capabilities to excel at continuous testing. This is where tools like JIRA and nTask Issue Tracker shine. They’ll offer features tailored to defect tracking while also helping you analyze QA team performance in real time so you can know how to increase efficiency and remain on schedule. Value-Driven Development You can only offer so much value if you aren't listening and responding to users. So to get better at value-driven development, you must create a smoother path for user feedback to be absorbed into the development lifecycle promptly. Photo by krakenimages on Unsplash One critical piece in this area is the usability testing tools you rely on. They should have functionality that speaks to agility, such as; Recruiting participants remotelyA/B testingIntegration with various tools like prototyping solutions, design tools, productivity tools and more. These are some of the crucial functions needed because: You want to be able to start user feedback collection from anywhere as soon as you get the green light. In that sense, participant recruitment should involve as little bureaucracy as possible and be easier to manage as you conduct more tests down the road. Testers should be able to compare feature variations side-by-side instead of testing one, then trying another later. So through A/B testing, you shorten the time it takes to discover whether a slight tweak in a feature caused a significant improvement in usability. Once you have user opinions and usability metrics, there shouldn't be that many error-prone processes to link the data to the concerned parties and the different tools they use to respond to the feedback. Whoever is going to modify a product should be able to quickly see how their previous contribution fared. The other leaders who have to sign off on additional changes should also be able to view this information simultaneously, so there isn't much sitting and waiting. Tools like UserZoom, Loop11, UsabilityHub, Userlytics and Maze will go a long way in helping you increase the customer value realized with each iteration. The glue that holds everything together While we’ve talked about the Agile QA process and Agile development software, another key aspect is more about the administrative side of an Agile project. When it comes to this area, you'll hear a lot of buzzwords and office terminology thrown around, like modularity, effective communication and visibility. But to be clearer about the tenets of organizational agility, here’s what Agile teams should emphasize during the development life cycle: Teams should be able to zoom in on the smallest of processes as this is how they'll know what's essential and what isn't and also what could be improved. Organizations should give more autonomy to the lower ranks so they can do some things at their discretion. If every small move has to first be run up a long chain of command, all in the name of maintaining control and minimizing risk, you can forget about faster releases. Whatever you practice should be incremental. For example, when figuring out how to communicate better, you don't just set benchmarks and lean back. Instead, you should revisit them to see if they are working and decide whether to maintain, increase, decrease or move sideways. So how exactly do these principles shape tool choices? Well, you’ll need Agile project management tools that offer features like automated notifications, workflow customization, analytics and recommendations. There are plenty of options to try; Agilean, ProofHub, ActiveCollab, MeisterTask, Axosoft, JIRA and DailyScrum. Wrapping Up Ultimately, tools that work for some may not work for you, so it starts with understanding your existing organizational culture and how much you're willing to alter it in pursuit of agility. That’s when you’ll know where tools are applicable and which functionality they must have. To learn more about how to pick the right developer and QA tools for Agile development, contact us for a free consultation.

      17/11/2022

      1.48k

      +0

        How Agile Development Influences Developer And QA Tool Choices

        17/11/2022

        1.48k

        What to consider when choosing languages for developing SaaS products

        +0

          What To Consider When Choosing Languages For Developing SaaS Products

          Over time, several programming languages have emerged as reliable tools that developers can use to bring software ideas to life. However, software end-users simply want a product that excels at solving the problem at hand. They don’t care that much about the ingredients and recipe behind it. Nevertheless, it’s extremely crucial to choose the right programming language when developing SaaS products. Making the wrong choice can lengthen the development lifecycle, produce a sub-par app and cost you even more money post-release as you try to fix several issues. With that in mind, let’s discuss the major factors to consider when choosing a programming language for developing a SaaS product: User-friendliness Even though software creation is mainly done by those with above-average tech-savviness, technology is supposed to make things easier for everyone. So if a programming language requires convoluted syntax spanning several lines just to create a basic instruction, the code will get clunky quickly. This makes it hard to follow, especially for newcomers who join the team while the project is already underway. And don’t forget that it will also be harder to document. Honestly, many languages can do much of what Python does, but Python remains a favorite for many developers due to its user-friendliness. This language tries to make coding resemble writing actual English commands as much as possible. User-friendliness also extends to functionality like code templates and the extent to which a language simplifies code reuse. Ecosystem The first part of the ecosystem to consider is supporting tools. Consider the variety of libraries you can hook up to the language you're using. Besides the libraries, there are documentation tools, automation tools, testing and quality assurance tools, and office/team productivity tools. The more tools a language can work with, the easier it is to take a piece of your work and run it through as many processes in your workflow, bringing it to readiness in the shortest time possible. In addition, strong integration capabilities also simplify intra-team and inter-team collaboration. For example, error detection, logging and subsequent communication happen more fluidly. The second part of the ecosystem to evaluate is the community. Find out how large and active the forums related to certain programming languages are. Communities encourage knowledge sharing, which helps you solve problems faster and at a lower cost while also opening your mind to new ingenious approaches that you can apply beyond an immediate challenge. Photo by Christopher Gower on Unsplash This is where open-source languages like JavaScript and Python beat the competition. According to Statista, JavaScript's community size reached 13.8 million developers by the end of 2021, while Python came in second with 10.1 million developers. Delivery Platform and Software Elements You need to ask yourself two critical questions when choosing a programming language for developing a SaaS product. One is, "On what platform/OS will the final product run?" For example, are you developing a product for Windows only, or do you want to cater to the Mac crowd too? The same goes for mobile, "Are you building for Android, iOS or both?" This question is particularly crucial because even though many frameworks can be used to develop cross-platform apps, such as React Native, Flutter or Xamarin, others stand out when developing apps for a specific platform. For instance, many developers find Swift to be one of the best options for developing iOS apps, and also like Kotlin for Android app development. Unfortunately, there’ll always be trade-offs regardless of the approach you take. If you go with a more universal cross-platform language, you’ll probably save money and release faster, but the product may not fully maximize one OS’s capabilities, especially when it comes to OS-specific APIs or performance-intensive processes. Furthermore, you may also have to spend some extra time fiddling with interpreters and libraries. But if you go the native route with an option highly geared toward a specific platform, you'll likely produce something that excels on that platform. Sadly, you may incur higher development costs and work slower. Secondly, it also helps to consider which aspects you'll focus on for your minimum viable product and other early iterations. For example, if your UX goals require a concerted effort on back-end development with a super lean front-end, you can start out with a language that is superb for back-end work and adequate for your simpler front-end goals. As you enhance the front end further down the road, you can spend more time exploring the valuable capabilities that differentiate Elm, TypeScript, CSS, HTML and other tools. Human Resources This factor may seem like one you have to deal with after you make a choice, but it's worth keeping an eye on from the get-go. For starters, some languages are newer and have fewer developers with high proficiency levels, which often means higher pay demands. Photo by Annie Spratt on Unsplash But then again, because some languages are more widely used, even the developers with preliminary knowledge have jobs most of the time. Consequently, the salary ranges for developers using languages like Python and Java remain pretty high. The trickier bit comes in when you intend to use multiple languages but you want to moderate the developer expenditure. Finding developers who are sufficiently skilled in the specific combination of languages you want to use might be harder. And if you do, you'll probably need them more than they need you, and they'll know it, so they won't hesitate to charge you highly. Wrapping Up Ultimately, the question of how to choose the right programming language remains a complex one. Technology constantly evolves, and many tools roll out new amazing functionality faster than you can blink. Moreover, some entirely new tools come onto the scene every now and then. So whatever you do, ensure that you have clear goals regarding the quality of the SaaS product you want to deliver and avoid shortcuts since they’ll probably cost you more later. Luckily, a professional team like SupremeTech can relieve you of the burden of which programming language to choose. You can contact us for a free consultation on the scope of software development solutions we provide.

          17/11/2022

          1.28k

          +0

            What To Consider When Choosing Languages For Developing SaaS Products

            17/11/2022

            1.28k

            How to exercise value-driven app development that drives revenue

            +0

              How To Exercise Value-Driven App Development That Drives Revenue

              Many software development teams spend long periods developing and rolling out features they've invested in, only to get lackluster results in customer satisfaction and overall revenue. On the other hand, some teams roll out a seemingly silly feature that eventually gets everyone giggling when using their app and drives more engagement. So how do some teams get it right while others fail? Let’s lay out some key value-driven app development strategies that can help you boost revenue: Involve industry experts When development teams are creating software for a client, they often talk to one person on the client’s side or a few people in higher managerial positions. Instead, they should be speaking to people at various levels of the organization to determine how one department's actions affect another department's work. Additionally, if the product isn't just for internal use by one client but for a whole industry, it's essential to talk to different people within that industry. This helps you learn what they are getting wrong individually and as a group. You can discover which approaches are unique to one organization and which workflow practices are industry-standard. From here, you’ll know the must-have features that appeal to a larger group, then create a list of optional features that highlight the ingenious ways a few entities in that industry are tackling inefficiencies. Consequently, you can test these extras individually to see if they'll be relevant for the whole industry or if they only worked for one organization due to their unique characteristics. Remember, HR in an ecommerce company won't be exactly the same as HR in a hospital, so if you know the product is aimed at a specific industry, find out that industry's major pain points before you start development. But what if the app is for the general public? So let’s say you’re trying to make the next WhatsApp or TikTok. In that case, it helps to speak to experts in fields like messaging and communication, behavioral psychology and other broad studies. You should also identify people who have previously worked at firms that do what you’re trying to improve. For example, a former PayPal worker could help you learn what’s missing in modern fintech products, depending on their role at the company. Define value at each stage It’s possible to make an app better in a particular area, like how fast it displays search results, but still not offer value. To create value and drive app revenue, you need to ask yourself, “What are users willing to pay for?” For example, many people are willing to pay for an app that helps them quickly get food from their favorite restaurants. So after ascertaining what people are paying for, find out what's missing in that product/service. What could be better than selecting the dish you want and receiving it quickly? The answer to this question starts with breaking down that entire process into various stages. These may include; finding a good dish, making changes to an order (increasing quantity, choosing different toppings, zinger or regular, extra cheese), notifying the provider that you aren't at your usual address, using alternative payment methods at checkout etc. By dividing the process into such stages, it's easier to determine what can go wrong in a particular phase or what can be added. Ultimately, something valuable changes the user's behavior in one way or another. For example, a favorites menu makes users spend less time scrolling through entire catalogs. They'll only do this when they are tired of their favorites. So in that sense, a better-looking strip of thumbnails might make a user feel good, but the ability to see which item is unavailable or which currently has a discount is more valuable. The ability to quickly see what's new, exclude items below or above a specific price, and other capabilities like that speak to someone who desires to pay. Therefore, whenever your team decides to improve an app, you should represent goals as something that induces an action that could culminate in a sale. For example, goals should sound like, "Make it possible to search by price," "Add option to change the delivery address for each order,” and "Add suggestions that would go well with the item ordered right before checkout.” Shorten the feedback loop It’s common for organizations to champion customer-centric product development, but listening to the user is only half the battle. To grow app revenue, you must transcend discovering what the people want and providing it. You should understand what they are saying and act on it faster than the competition. To achieve this, you ought to categorize feedback based on different criteria, such as; How detailed is it? Is it a score or an entire paragraph?Is it a request for a new feature, a review of the whole app or a small comment on how responsive and helpful an existing feature is?How much does it cost to collect that feedback (the tech tools you need, the amount of time you spend collecting data, the number of people involved in the process and more)? Teams often need to pay more attention to how organized they need to be to collect user opinions or observe and analyze user behavior. They need to remember that it can be tricky to put together a representative focus group, find a usability testing tool that tracks indicators in the desired manner, communicate feedback across the team and arrange meetings to brainstorm in response. By categorizing feedback, it's easier to visualize the entire journey of a user's opinion, the time it's received, and the different people that weigh in on how to respond to it up until it manifests in the next version of the product. Subsequently, you spend less time collecting irrelevant data or sitting on important information. Wrapping Up Value is subjective. This is what makes value-driven app development quite challenging. At the end of the day, there'll always be some hit-and-miss scenarios, but if you want professional help practicing value-driven app development that drives revenue, contact us for a free consultation.

              08/11/2022

              1.05k

              +0

                How To Exercise Value-Driven App Development That Drives Revenue

                08/11/2022

                1.05k

                Feature (Web) - Top emerging trends in app UI design (2023 OUTLOOK)

                +0

                  Top Emerging Trends In App UI Design (2025 OUTLOOK)

                  While an app is made with a specific group of people in mind, that is, people who have a problem that the app solves, its user interface has to consider the existence of several sub-groups within that group. UI designers have to ask themselves a wide range of questions, such as: “Does everyone understand what a certain symbol means?” “Could there be an end-user who is blind?” “Will everyone be able to see this button or read this language?” On top of that, they also have to consider business interests like branding and cost efficiency. So, how are they getting better at harmonizing all this? To answer that, let’s discuss the emerging trends in app UI design through the SupremeTech article. Augmented Reality (AR) AR is gradually becoming a more common aspect of various app UIs, particularly because of its wide range of possibilities when using real graphics to communicate. This technology shows that you can communicate quickly and induce different responses by superimposing extra graphics onto an image or video of an actual entity captured. For example, you can create something that’s funny because it's not real, like showing yourself with dog ears or a flower crown. On the contrary, you can also create something that's captivating because it's almost real, like a view of your living room with a couch or your face with makeup. AR gives you a chance to visualize elements you'd otherwise have to put together physically and does so with unprecedented accuracy such that the imaginary representation is as close to the real thing as possible. Some examples of excellent AR usage include Modiface, See My Fit/Virtual Catwalk, IKEA Studio, Amazon Salon, Snapchat, Gucci Sneaker Garage, View in Room and Asian Paints. Voice UI Technically, Voice UI isn't entirely new. For a while, many software tools could respond to commands with something like an error message or instruction in audio form. However, what's changed recently is that thanks to artificial intelligence, users can converse with the software on a device. This is already in use with Google Assistant, Siri and Alexa, but there’s still room to expand. For example, designers can create interfaces that automatically pick up ambient noise in a room and use it as a guideline for adjusting music volume or as a trigger for something else, like a display of birthday party graphics and lighting when a crowd yells “Surprise.” Virtual Reality (VR) VR takes the concept of visualization one step further by immersing you into the space you’re viewing rather than simply pasting it onto a screen. It enables you to perceive dimensional changes when you move within a space, like an object getting closer or farther away. It's one thing seeing an object at the end of a room on a screen while being told the length and width of the room. However, it’s totally different when you’re actually in the room. You’re no longer trying to extrapolate from a smaller image on a screen that is also a certain distance away from your eyes. VR's capabilities are handy when trying to remotely touring a house. Moreover, it is about more than just viewing objects. VR can be used to relay commands that involve body movements, which makes it ideal for use cases like rehearsing a surgical procedure or assembling and repairing an intricate machine. Some good VR apps include Provata VR, Space Explorers, Tilt Brush, and Gravity Sketch. VR is also common in the gaming world. >>> Maybe you are interested: Top 10 Design Tools For UX And UI (2025 GUIDE)Differences In UX Demands Of A Desktop And Mobile App For A SaaS ProductAtomic Design In Software Development Haptic Feedback Haptic Feedback is designed to address a user through their sense of touch. In that sense, haptic feedback messages are usually conveyed as vibrations within the device a user handles. Initially, this technology was used in a basic manner, like notifying someone that they are being called if their phone is in silent mode or that they've chosen the right or wrong option on a screen. Later, it advanced into an exciting way to keep a user engaged by trying to simulate what it’s like to be in a particular situation, like the rattle in a car when it leaves a smooth tarmac track and goes off-road onto a rough and bumpy Murram strip. This use case has been prevalent in gaming controllers. Nevertheless, haptic feedback continues to evolve, with companies like NewHaptic using this technology to create fluid Braille touch screens that use tactile pixels (taxes). Clearly, haptic feedback could be a great tool for making apps more accessible to people with disabilities. Additional trends Many other UI trends are impressive, even though they may not have the most significant impact on user behavior. These include a dark mode, flat UI, glass morphism, metamorphism, animated illustrations, buttonless design and minimalism, asymmetrical layouts, and more. Ultimately, UI is an intersection of expression and technology, which means many designers will come across the same concepts, but the difference will be in execution. On that note, here are a few questions to answer before you jump onto a UI trend: Does it make life any easier for the user, or is it merely a fancy nice-to-have?What does it say about your brand? (futuristic, sleek, nostalgic, sexy, young and vibrant, sophisticated etc.)How much computing resources does it require? (Will it end up slowing down the app and making it heavier, or will everything still run smoothly)Is it inclusive, or does it speak to the strengths of a few while sidelining many who have a specific weakness?How much money will it cost to install and maintain? Lastly, remember that UI design goes hand-in-hand with many other elements of a software product. For instance, an e-commerce app's item display may require a slider to see different angles of a product, while a fitness app may only need a thumbnail for each workout. There are other considerations, like whether the subtle tones of neomorphic buttons would work well for a CTA, which usually needs to stand out. Wrapping Up UI design is a far-reaching aspect of app development that often requires various team members’ input. This can be tricky to execute while responding to changes in user demands and other project challenges during the development lifecycle. If you need professional guidance on addressing every facet of app UI design, contact us for a free consultation.

                  08/11/2022

                  1.77k

                  +0

                    Top Emerging Trends In App UI Design (2025 OUTLOOK)

                    08/11/2022

                    1.77k

                    prd-thumb-draft-product

                    +0

                      TypeScript And “Any” Type

                      TypeScript is a strongly typed programming language that builds on JavaScript, giving you a better ability to detect errors and describe your code. But sometimes you don't know the exact type of value that you're using because it comes from user input or a third-party API. In this case, you want to skip the type checking and allow the value to pass through the compile check. The TypeScript any type is the perfect solution for you because if you use it, the TypeScript compiler will not complain about the type issue. This blog will help you understand the any type in TypeScript, but before doing that, let's begin with some basic concepts! What is TypeScript? TypeScript checks a program for errors before execution and does so based on the kinds of values; it’s a static type checker. Superset of JavaScript TypeScript is a language that is a superset of JavaScript: JS syntax is, therefore, legal TS. However, TypeScript is a typed superset that adds rules about how different kinds of values can be used. Runtime Behavior TypeScript is also a programming language that preserves JavaScript's runtime behavior. This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks the code has type errors. Erased Types Roughly speaking, once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting compiled code. This means that once your code is compiled, the resulting plain JS code has no type information. An easy way of understanding TypeScript A languageA superset of JavaScriptPreserver the runtime behavior of JavaScriptType checker layer JavaScript + Types = TypeScript Basic typing Type annotations TypeScript uses type annotations to explicitly specify types for identifiers such as variables, functions, objects, etc. // Syntax : type Once an identifier is annotated with a type, it can be used as that type only. If the identifier is used as a different type, the TypeScript compiler will issue an error. let counter: number; counter = 1; counter = 'Hello'; // Error: Type '"Hello"' is not assignable to type 'number'. The following shows other examples of type annotations: let name: string = 'John'; let age: number = 25; let active: boolean = true; // Array let names: string[] = ['John', 'Jane', 'Peter', 'David', 'Mary']; // Object let person: { name: string; age: number }; person = { name: 'John', age: 25 }; // Valid // Function let sayHello : (name: string) => string; sayHello = (name: string) => { return `Hello ${name}`; }; Type inference Type inference describes where and how TypeScript infers types when you don’t explicitly annotate them. For example: // Annotations let counter: number; // Inference: TypeScript will infer the type the `counter` to be `number` let counter = 1; Likewise, when you assign a function parameter a value, TypeScript infers the type of the parameter to the type of the default value. For example: // TypeScript infers type of the `max` parameter to be `number` const setCounter = (max = 100) => { // ... } Similarly, TypeScript infers the return type to the type of the return value: const increment = (counter: number) => { return counter++; } // It is the same as: const increment = (counter: number) : number => { return counter++; } The following shows other examples of type inference: const items = [0, 1, null, 'Hi']; // (number | string)[] const mixArr = [new Date(), new RegExp('\d+')]; // (RegExp | Date)[] const increase = (counter: number, max = 100) => { return counter++; }; // (counter: number, max?: number) => number Contextual typing TypeScript uses the locations of variables to infer their types. This mechanism is known as contextual typing. For example: document.addEventListener('click', (event) => { console.log(event.button); // Valid }); In this example, TypeScript knows that the event the parameter is an instance of MouseEvent because of the click event. However, when you change the click event to the scroll the event, TypeScript will issue an error: document.addEventListener('scroll', (event) => { console.log(event.button); // Compile error }); // Property 'button' does not exist on type 'Event'. TypeScript knows that the event in this case, is an instance of UIEvent, not a MouseEvent. And UIEvent does not have the button property, therefore, TypeScript throws an error. Other examples of contextual typing // Array members const names = ['John', 'Jane', 'Peter', 'David', 'Mary']; // string[] names.map(name => name.toUpperCase()); // (name: string) => string // Type assertions const myCanvas = document.getElementById('main-canvas') as HTMLCanvasElement; Type inference vs Type annotations Type inferenceType annotationsTypeScript guesses the typeYou explicitly tell TypeScript the type What exactly is TypeScript any? When you don’t explicitly annotate and TypeScript can't infer exactly the type, that means you declare a variable without specifying a type, TypeScript assumes that you use the any type. This practice is called implicit typing. For example: let result; // Variable 'result' implicitly has an 'any' type. So, what exactly is any? TypeScript any is a particular type that you can use whenever you don't want a particular value to cause type-checking errors. That means the TypeScript compiler doesn't complain or issue any errors. When a value is of type any, you can access any properties of it, call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal: let obj: any = { x: 0 }; // None of the following lines of code will throw compiler errors. // Using `any` disables all further type checking, and it is assumed // you know the environment better than TypeScript. obj.foo(); obj(); obj.bar = 100; obj = 'hello'; const n: number = obj; Looking back at an easier-to-understand any: A special type.Skip/Disable type-checking.TypeScript doesn't complain or issue any errors.Default implicit typing is any. Note that to disable implicit typing to the any type, you change the noImplicitAny option in the tsconfig.json file to true. Why does TypeScript provide any type? As described above, while TypeScript is a type checker, any type tells TypeScript to skip/disable type-checking. Whether TypeScript has made a mistake here and why it provides any type? In fact, sometimes the developer can't determine the type of value or can't determine the return value from the 3rd party. In most cases they use any type or implicit typing as any. So they seem to think that TypeScript provides any to do those things. So, is that the root reason that TypeScript provides any? Actually, I think there is a more compelling reason for TypeScript providing any that the any type provides you with a way to work with the existing JavaScript codebase. It allows you to gradually opt-in and opt out of type checking during compilation. Therefore, you can use the any type for migrating a JavaScript project over to TypeScript. Conclusion TypeScript is a Type checker layer. The TypeScript any type allows you to store a value of any type. It instructs the compiler to skip type-checking. Use the any type to store a value when you migrate a JavaScript project over to a TypeScript project. In the next blog, I will show you more about the harmful effects of any and how to avoid them. Hope you like it! See you in the next blog! Reference TypeScript handbookTypeScript tutorial Author: Anh Nguyen

                      07/09/2022

                      1.87k

                      +0

                        TypeScript And “Any” Type

                        07/09/2022

                        1.87k

                        React application rs

                        +0

                          A Better Way To Use Services In React Application

                          Sometimes you have/want to create and use a service in your application for the DRY principle. But do you know exactly what is a service? And what is the best way to use services in React applications? Hi everyone! It's nice to meet you again in React related series. In the previous article, we discussed about effective state management in React, we learned about Context: what is it? when to use it? One of the use cases is using a context to share a collection of services through the components tree, but what kind of things can be called a service? And how is it integrated into React application? Let's discover the following sections: What is a Service? Service is just a group of helper functions that handle something particularly and can be reused across application, for example: Authentication Service that includes authentication status checking, signing in, signing out, getting user info …Http Service that handles request header, request method, request body … How to use? There are different kinds of implementation and usage, I just provide my favorite one that follows Angular module/services provider concepts. Create a service A service is a JavaScript regular class, nothing related to React. export default class ApiService { constructor() {} _setInterceptors() {} _handleResponse_() {} _handleError_() {} get() {} post() {} put() {} delete() {} } export default class AuthService { constructor() {} isAuthenticated() {} getUserInfo() {} signIn() {} signOut() {} } Create a Context Create a context with provider and pass services as props. import { createContext, useState } from 'react'; import { ApiService, AuthService } from '@services'; const services = { apiService: new ApiService(), authService: new AuthService() }; const AppContext = createContext(); const { Provider } = AppContext; const AppProvider = ({ children }) => { return <Provider value={{ services }}>{children}</Provider>; }; export { AppContext, AppProvider } Use a context Place a context provider at an appropriate scope, all consumers should be wrapped in it. import { AppProvider } from './context/AppContext'; import ComponentA from './components/ComponentA' const App = () => { return ( <AppProvider> <div className="app"> <ComponentA /> </div> </AppProvider> ); }; export default App; Inside a child component, use React hooks useContext to access services as a context value. import { useContext, useEffect } from 'react'; import { AppContext } from '../context/AppContext'; const ChildComponent = () => { const { services: { apiService, authService } } = useContext(AppContext); useEffect(() => { if (authService.isAuthenticated()) { apiService.get(); } }, []); return <></>; } export default ComponentA; Above are simple steps to integrate services with context. But it would be complicated in the actual work. Consider organizing context with approriate level/scope. My recommendation is to have two kinds of service contexts in your application: App Services Context to put all singleton services. Bootstrap it once at root, so only one instance for each is created while having them shared over the component tree.For others, create separate contexts and use them anywhere you want and whenever you need. Alternatives Service is not the only one way to deal with reusable code, it depends on what you intend to do, highly recommend to: Use a custom hook, if you want to do reusable logic and hook into a state.Use a Higher-order component, if you want to do the same logic and then render UI differently. Reference Does React Context replace React Redux?React RetiX - another approach to state management Author: Vi Nguyen

                          31/08/2022

                          7.01k

                          Vix Nguyen

                          +0

                            A Better Way To Use Services In React Application

                            31/08/2022

                            7.01k

                            Vix Nguyen

                            context-or-redux

                            +0

                              Does React Context Replace React Redux?

                              Table of contents What is Context?How and when to use a Context?When to use Redux?Does Context replace Redux? context-or-redux-1024x768 As you all know, nowadays, React has become one of the most famous JavaScript libraries in the world. It's easy to learn and use. It comes with a good supply of documentation, tutorials, and training resources. Any developer who comes from a JavaScript background can easily understand and start creating web apps using React in a few days with the main concepts: JSXRendering ElementsComponents and PropsState and LifecycleHandling Events But to become an expert in React, it would take more time. You have to deep dive into advanced things: Higher-Order componentsContextCode-SplittingAvoiding unexpected rerenderEspecially, Effective state management When it comes to state management in React applications, we instantly think about React Redux. This is a favorite and widespread tool across developer's communities and applications. Recently, a lot of questions have come to us about using React Context as an alternative for React Redux. To answer those questions, have a brief of React Context first. What is the context? The context was originally introduced for passing props through the component tree, but since newer versions, React provided the powerful feature that allows updating context from a nested component. Meanwhile, Context can now be a state management tool. Let's see how easy it works? Context with Hooks There are many ways to integrate Context, in this article, I just demo the simplest one Create a context import { createContext } from 'react'; export const ThemeContext = createContext(defaultTheme); So simple, createContext is the built-in function that allows you to create a context with default value. Create a provider A provider allow consuming components to subscribe to context changes const { Provider } = ThemeContext; const ThemeProvider = ( { children } ) => { const theme = { ... }; return <Provider value={{ theme }}>{children}</Provider>; }; Create a consumer The simplest way to subscribe to the context value is to use the useContext hook. export const ThemeInfo = () => { const { theme } = useContext(ThemeContext); return ( <div>backgroundColor: {theme?.background}</div> ); } A consumer must be wrapped inside a Provider if not it would not be noticed and then re-render when context data changes. <App> <ThemeProvider> <ThemeInfo></ThemeInfo> </ThemeProvider> </App> Update the context from a consumer It is sometimes necessary to update the context from consumers, context itself doesn't provide any method to do that, but together with hooks, it can be easy: Use useState to manage context valuesetTime is passed as a callback const { Provider } = ThemeContext; const ThemeProvider = ( { children } ) => { const [theme, setTheme] = useState(defaultTheme); return <Provider value={{ theme, setTheme }}>{children}</Provider>; }; From a consuming component, we can update the context value by executing the callback provided by context export const ButtonChangeTheme = () => { const { setTheme } = useContext(ThemeContext); return ( <button onClick={() => setTheme(newTheme)}>Change</button> ); } Again, don't forget to wrap ButtonChangeTheme consumer inside ThemeProvider <App> <ThemeProvider> <ButtonChangeTheme></ButtonChangeTheme> </ThemeProvider> </App> When to use context? As official guideline Context is designed to share data that can be considered global for a tree of React components. Below are common examples of data that Context can cover: Application configurationsUser settingsAuthenticated userA collection of services How to use context in a better way? As mentioned before, when the context value changes, all consumers that use the context will be immediately re-rendered. So putting it all into one context is not a good decision. Instead, create multi-contexts for different kinds of data. EX: one context for Application configurations, one for Authenticated user and others.Besides separating unrelated contexts, using each in its proper place in the component tree is equally significant.Integrate context adds complexity to our app by creating, providing, and consuming the context, so drilling props through 2-3 levels in a tree component is not a problem(Recommended to use instead of context)Restrictively apply context for high-frequency data updated, because context is not designed for that.​ What about React Redux? Unlike Context, React Redux is mainly designed for state management purposes, and covers it well. However, take a look at some highlights from Redux team: Not all apps need Redux. It's important to understand the kind of application you're building, the kinds of problems that you need to solve, and what tools can best solve the problems you're facing. You'll know when you need Flux. If you aren't sure if you need it, you don't need it. Don't use Redux until you have problems with vanilla React. Those recommendations clearly answer the question: When to use Redux? Conclusion So, Does React Context replace React Redux? The short answer is no, it doesn’t. React Redux and React Context can be used together instead of as alternatives. But how to use them together? It depends. If you understand the main concepts for each: React Context is designed for props drilling, it also has ways to update context data, but is recommended to deal with the simple follow of data changes.Redux is built for state management, especially for the frequently updated states used at many places in the application. Based on that you can easily decide what should be implemented in your application. In the end, try to use Context first, if something is not covered by Context, it's time to use Redux. Enjoy coding! Reference Context official docsRedux FAQ: generalIf you are not interested in using Redux, you can check out React RetiX for a different approach to state management.I can not remember all the sources I have read, but it helps a lot in having comparison between Context and Redux. Thank you and sorry for not listing them all in this article!​ Author: Vi Nguyen

                              17/06/2022

                              2.26k

                              +0

                                Does React Context Replace React Redux?

                                17/06/2022

                                2.26k

                                API_introduction_img_001

                                +0

                                  Giới Thiệu Về API Là Gì?

                                  Xin chào các bạn, mình là Thắng, thành viên team QC của SupremeTech. Trong bài viết này, mình sẽ giải thích cho các bạn về một khái niệm rất quen thuộc trong kiểm thử nói riêng mà còn trong ngành IT nói chung, đó là API. Mình nhớ khoảng thời gian đầu tiên khi mình bắt đầu nhận việc trong một dự án với yêu cầu chỉ có API; lúc đó mình còn chưa có đủ kiến thức và kinh nghiệm cùng với sự tự tin về mảng này. Có rất nhiều câu hỏi trong đầu mình như phải tìm hiểu thế nào? Kiểm thử ra sao? Và sau đó mình đã cố gắng học hỏi và thực hành rất nhiều, sau cùng mình nhận ra API không quá khó như lúc đầu mình nghĩ, ít nhất mình đã có được kinh nghiệm và kiến thức để tự tin áp dụng vào trong dự án. Ở đây, mình sẽ chia sẻ lại cho các bạn những gì mình đã tìm hiểu, đã áp dụng vào thực tế, để mọi người có góc nhìn khác khi một tester nhìn vào API thì sẽ như thế nào nhé. API là gì? API là viết tắt của cụm từ Giao diện lập trình ứng dụng (Application Programming Interface). API cung cấp khả năng truy xuất đến một tập các hàm hay dùng. Và từ đó có thể trao đổi dữ liệu giữa các ứng dụng. Một cách dễ hiểu thì API là một trung gian phần mềm cho phép hai ứng dụng giao tiếp với nhau. Ví dụ về API trong thực tế Tưởng tượng bạn bước vào một nhà hàng, bạn đặt món, nhân viên phục vụ sẽ tiếp nhận yêu cầu của bạn và đưa vào nhà bếp, sau đó sẽ mang ra món ăn đúng với yêu cầu của bạn. Trong ví dụ trên, API là nhân viên phục vụ, đã giúp bạn và đầu bếp giao tiếp với nhau. Bây giờ hãy nghĩ về một trường hợp ứng dụng API trong thực tế nhé. Giả sử bạn đi du lịch, bạn sẽ vào trang web của các hãng hàng không nhằm kiểm tra chuyến bay, giá cả, số ghế,… Nhưng vấn đề ở đây là có quá nhiều hãng hàng không và bạn lại không muốn mất thời gian cho những việc thế này, thay vào đó, bạn có thể sử dụng các dịch vụ trực tuyến trung gian nhiều tiện ích như Traveloka hay Expedia. Những dịch vụ đó sẽ tương tác với API của các hãng hàng không để hiển thị cho bạn các thông tin liên quan không chỉ của một mà còn của nhiều hãng bay khác nhau, từ đó giúp cho bạn tiết kiệm được rất nhiều gian và công sức. API thật tuyệt vời đúng không! HTML là gì? Khoảng thời gian sau khi World Wide Web (WWW) được ra đời vào cuối những năm 1980, nhu cầu trao đổi dữ liệu giữa các thiết bị điện tử trở nên phát triển hơn bao giờ hết. Vào thời điểm đó, các tập tin siêu văn bản HTML được đưa lên web và người sử dụng có thể đọc được nội dung một cách dễ dàng. HTML là viết tắt của từ HyperText Markup Language - Ngôn ngữ Đánh dấu Siêu văn bản. Đây là một loại ngôn ngữ nhằm định dạng trang web thông qua các thẻ (tag) nhằm giúp cho máy tính hiểu được bố cục và cấu trúc của trang web và hiển thị trang web đó. Tuy nhiên lập trình viên chỉ có thể sử dụng những tag được quy định sẵn trong HTML khiến cho việc mở rộng hay tạo ra những nội dung mới trên website khá khó khăn. Một vấn đề khác nữa là HTML chỉ đơn thuần là ngôn ngữ trình bày nội dung, nó không có chức năng lưu trữ hay trao đổi dữ liệu giữa các máy tính với nhau, nghĩa là các hệ thống không thể tương tác với nhau như cập nhật giá cả hàng ngày chẳng hạn. XML là gì? Do đó XML - Extensible Markup Language được ra đời với sứ mệnh tạo ra các tài liệu web cho cả người và máy tính đều có thể dễ dàng đọc được, khiến Internet thực sự trở thành một mạng lưới liên kết đúng nghĩa thật sự. XML được phát triển bởi mười một người đóng góp tại W3C vào năm 1997. XML, đúng như tên gọi của nó (Extensible - mở rộng), đã giải quyết được một vài vấn đề của HTML như thay vì sử dụng các tag có sẵn thì XML cho phép các lập trình viên tự tạo ra các tag của chính mình, từ đó cho phép họ thể hiện được nhiều nội dung hơn trên website, và đặc biệt là XML cho phép gói dữ liệu vào trong nội dung văn bản và trao đổi giữa các hệ thống với nhau. Trước khi XML ra đời thì các hệ thống vẫn có thể trao đổi dữ liệu với nhau nhưng đó là một quy trình rất phức tạp và phải thống nhất rất nhiều quy tắc, dẫn tới việc nếu trao đổi dữ liệu lớn thì sẽ xảy ra tình trạng bị mất dữ liệu trong lúc chuyển đổi. Với XML, lập trình viên có thể khai báo trước các tag của mình và các hệ thống đều có thể đọc được và tương tác với nhau dễ dàng hơn. Mình sẽ lấy một ví dụ đơn giản cho bạn dễ hiểu nhé. Trong HTML có một thẻ tag là <title> nhằm khai báo tiêu đề trang web. Cấu trúc sẽ như thế này: <!DOCTYPE html> <html> <head> <title>Supremetech blog</title> </head> <body> </body> </html> Trong khi đó, với XML bạn có thể tự khai báo thẻ tag <title> với nhiều mục đích khác nhau như tiêu đề trang web và tiêu đề một quyển sách hiển thị trên trang web đó mà không lo bị lỗi: <?xml version="1.0" encoding="UTF-8"?> <page> <head> <title>Book store</title> </head> <body> <library> <book> <title>Harry Potter</title> <author>J.K Rowling</author> </book> <book> <title>Sherlock Holmes</title> <author>Conan Doyle</author> </book> </library> </body> </page> Các bạn có thể thấy thẻ tag <title> nằm trong thẻ <head> sẽ được máy tính hiểu là tiêu đề của trang, còn thẻ <title> nằm trong thẻ <book> sẽ được hiểu là tiêu đề của quyển sách. SOAP và RESTful Sau khi hiểu được API là gì, các bạn sẽ thấy API vô cùng quan trọng trong thời đại số như hiện nay. Và như một điều hiển nhiên, mọi thứ sau khi phát triển một thời gian sẽ hình thành những quy tắc chung. Sau đây mình sẽ giới thiệu 2 chuẩn phổ biến là SOAP là RESTful. SOAP Sau khi XML ra đời, một vài kỹ sư tại Microsoft đã phát triển SOAP. SOAP là một tiêu chuẩn dựa hoàn toàn vào XML để chuẩn hóa việc giao tiếp giữa server và thiết bị (client), từ đó giúp cho việc phát triển API tốt hơn. Sau khi SOAP xuất hiện, đặc biệt vào năm 2000, SOAP đã được Microsoft và IBM thúc đẩy và trở nên phổ biến. Một số công ty và các tập đoàn lớn đã sử dụng SOAP như HP hay Oracle cho các chương trình của họ. Một vấn đề khá lớn của SOAP là có quá nhiều quy tắc phải tuân thủ khiến cho lập trình viên thấy nó quá khó để sử dụng. Mặc dù việc có nhiều quy tắc cũng là một ưu điểm của SOAP bởi vì nhờ đó các lập trình viên có thể tạo ra các hệ thống độc lập nhưng vẫn giao tiếp tốt với nhau. Từ khả năng giao tiếp tốt đó, các hệ thống lớn gồm nhiều hệ thống liên quan sẽ được quản lý và phát triển một cách dễ dàng hơn. RESTful Một nhà khoa học máy tính tên Roy Fielding đã nhìn ra vấn đề đó và giới thiệu tiêu chuẩn REST trong luận văn tiến sĩ của mình với mục đích duy nhất: tạo ra tiêu chuẩn giúp cho các server đều có thể giao tiếp được với nhau. Nếu như SOAP sử dụng XML để tạo request và response thì RESTful có thể tạo request với một URL đơn giản đi cùng với các phương thức (method) như GET, POST, PUT, DELETE và response trả về cũng được viết ở nhiều dạng như JSON hay CSV. Bạn hãy nhìn vào ví dụ dưới đây về request và response của API dùng để xem giá cả nếu được viết dưới dạng XML theo tiêu chuẩn SOAP: Request <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding"> <soap:Body> <m:GetPrice xmlns:m="https://www.w3schools.com/prices"> <m:Item>Apples</m:Item> </m:GetPrice> </soap:Body> </soap:Envelope> Response: <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding"> <soap:Body> <m:GetPriceResponse xmlns:m="https://www.w3schools.com/prices"> <m:Price>1.90</m:Price> </m:GetPriceResponse> </soap:Body> </soap:Envelope> Source: W3C Rất là rắc rối và phức tạp đúng không nào. Trong khi đó nếu ta cũng dùng API gọi thông tin về giá sản phẩm theo RESTful thì chỉ cần gửi request tới URL (https://www.w3schools.com/prices), chọn method là GET thì sẽ có response dưới dạng JSON như sau: { "Apple": "1.90" } Nhìn vào API theo tiêu chuẩn RESTful bạn cũng nhận ra nó đơn giản và dễ dùng hơn SOAP đúng không? Đó là lí do mà vì sao RESTful được sử dụng rất nhiều vào ngày nay. Một lí do khác là vào thời điểm những năm 2000, Internet phát triển cực kì mạnh mẽ, đặc biệt là mảng thương mại điện tử. Rất nhiều tập đoàn lớn lúc đó đã phát triển API của mình để nhiều bên có thể truy cập vào dữ liệu sản phẩm của họ. Lúc đó Salesforce là một trong những người tiên phong cung cấp API của mình dưới tiêu chuẩn SOAP nhưng lại không được nhiều lập trình viên ưa chuộng vì tài liệu hướng dẫn sử dụng hơn 400 trang. Trong khi đó, Ebay, mặt khác lại cung cấp API theo chuẩn RESTful và đã đạt được sự thành công đáng kể so với đối thủ là Salesforce lúc bấy giờ khi mà nhiều bên cảm thấy API theo chuẩn RESTful dễ truy cập và dễ sử dụng. Kể từ đó là thời kì phát triển mạnh mẽ của RESTful API, nhiều ông lớn đã đi theo Ebay như Amazon, Flickr,… Dưới đây là sơ đồ thống kê mức độ phổ biến các chuẩn API vào năm 2014: Source Dưới góc độ kiểm thử và sự phổ biến của RESTful nên mình sẽ nói kỹ hơn về chuẩn này nhé. Hình ví dụ ở trên minh họa một cách đơn giản về nguyên lý hoạt động của API theo tiêu chuẩn RESTful. Hãy lấy lại ví dụ ở phần trước đó về việc bạn sử dụng Traveloka để xem thông tin về chuyến bay nhé. Bạn vào mục tra cứu chuyến bay trên web Traveloka, sau bước này thì website - client sẽ gửi request theo giao thức HTTP tới server của hãng bay. Tùy thuộc vào phương thức - method bạn gửi thì server sẽ có những xử lý tương ứng. Trong RESTful sẽ có 4 phương thức cơ bản sau đây: GET (SELECT): Trả về một Resource hoặc một danh sách Resource.POST (CREATE): Tạo mới một Resource.PUT (UPDATE): Cập nhật thông tin cho Resource.DELETE (DELETE): Xoá một Resource. Những phương thức hay hoạt động này thường được gọi là CRUD tương ứng với Create - Tạo, Read - Đọc, Update - Sửa, Delete - Xóa. Ví dụ ở đây bạn muốn xem thông tin về chuyến bay thì method client dùng sẽ là GET nhằm lấy về danh sách các chuyến bay theo yêu cầu của bạn. Sau khi server nhận được request của Client sẽ tiến hành trả về dữ liệu phù hợp response. Dữ liệu trả về thường được viết dưới dạng JSON hoặc XML tùy thuộc vào tính chất của dự án. Dữ liệu trả về gồm có cấu trúc như sau (mình sẽ để dưới dạng JSON nhé): { "status_code": 200, "data": [ { "name": "LH370", "Time": "Mar 29, 2022", "City": "DNG" }, { "name": "LH370", "Time": "Mar 29, 2022", "City": "HCM" } ], } Các bạn có thể thấy ở response có dòng “status_code”, biến này sẽ cho chúng ta biết được trạng thái của response trả về. Các mã sẽ được phân thành các nhóm như sau: 2xx: Successful responses / Phản hồi thành công:200 OK – Trả về thành công cho những phương thức GET, PUT, PATCH hoặc DELETE.201 Created – Trả về khi một Resource vừa được tạo thành công.204 No Content – Trả về khi Resource xoá thành công.3xx: Redirects / Điều hướng304 Not Modified – Client có thể sử dụng dữ liệu cache.4xx: Client errors / Lỗi phía client400 Bad Request – Request không hợp lệ401 Unauthorized – Request cần có auth.403 Forbidden – bị từ chối không cho phép.404 Not Found – Không tìm thấy resource từ URL5xx: Server errors / Lỗi phía máy chủ500 Server Error: domain, hosting hết hạn, hoặc dừng server đột ngột để test502 Bad Gateway503 Service Unavailable Web services là gì? Phân biệt API và web services Và lúc này khái niệm web services trở nên phổ biến. Giờ chúng ta tìm hiểu thêm một khái niệm mới nhé. Nói một cách khái quát, web services là những tài nguyên có sẵn trên internet, là dịch vụ cung cấp một số chức năng mà các ứng dụng khác có thể sử dụng. Chức năng này có thể bao gồm xử lý thanh toán, đăng nhập và lưu trữ cơ sở dữ liệu. Cả API và web services đều đóng vai trò giúp cho các ứng dụng giao tiếp được với nhau. Điểm khác biệt cơ bản giữa API và web services đó là web services giúp các ứng dụng giao tiếp với nhau trên Internet nhưng API có thể giúp các ứng dụng giao tiếp với nhau mà không cần Internet. Chúng ta có thể nói tất cả web services là API nhưng không phải API nào cũng là web services. Hơi rắc rối đúng không nào, mình sẽ lấy một ví dụ cho bạn dễ hình dung nhé: Hầu như trong cuộc sống ngày nay chúng ta luôn có sẵn ứng dụng Facebook trên điện thoại của mình. Khi bạn bắt gặp một khoảnh khắc nào đó và muốn chụp một bức hình để chia sẻ cho bạn bè cũng xem, bạn sẽ bấm vào biểu tượng máy ảnh trên Facebook và nó sẽ mở màn hình chụp ảnh cho bạn. Lúc này Facebook sẽ gọi API máy ảnh của điện thoại để sử dụng máy ảnh ngay trên ứng dụng mà không cần phải mở app chụp ảnh mặc định của điện thoại, và việc gọi API này thì không cần mạng. Ở một trường hợp khác, khi bạn vào xem thông tin một địa điểm nào đó trên Facebook thì sẽ thấy bản đồ chỉ đường tới địa điểm đó đúng không? Lúc đó Facebook sẽ gọi API (web services) từ Google Map để lấy thông tin bản đồ về và thao tác này chắc chắn cần mạng mới có thể làm được. Cho tới hiện tại, việc tranh cãi SOAP hay RESTful tốt hơn vẫn chưa hề kết thúc. Tùy thuộc vào tính chất của dự án và sở thích của lập trình viên mà chúng ta sẽ lựa chọn chuẩn phù hợp. SOAP có thể phức tạp, phải tuân thủ nhiều quy tắc nhưng đôi khi nó lại dễ sử dụng trong một số trường hợp, còn đàn em của nó là RESTful nổi lên như một giải pháp thay thế mới mẻ song vẫn có những vấn đề của riêng nó. Bài viết giới thiệu về API của mình đến đây là hết, mình rất vui vì một phần nào đó đã giúp các bạn có thêm những kiến thức mới. API theo chuẩn RESTful rất phổ biến, do đó kĩ năng kiểm thử API theo chuẩn này rất cần thiết với tester. Những bài viết tiếp theo mình sẽ giới thiệu cho các bạn về những công cụ thường được sử dụng trong việc test API như Postman, Charles,… Hẹn gặp lại các bạn lần sau! Reference W3schools (no date) W3schools.com, W3Schools Online Web Tutorials. Available at: https://www.w3schools.com/xml/xml_soap.asp (Accessed: 04 October 2024).Jay (2023) Soap and rest at odds, The History of the Web. Available at: https://thehistoryoftheweb.com/soap-rest-odds/ (Accessed: 04 October 2024).Harrington, D. (2024) The history of rest apis - readme: Resource library, ReadMe. Available at: https://readme.com/resources/the-history-of-rest-apis (Accessed: 04 October 2024). Author: Thang Tran

                                  22/04/2022

                                  1.42k

                                  +0

                                    Giới Thiệu Về API Là Gì?

                                    22/04/2022

                                    1.42k

                                    Customize software background

                                    Want to customize a software for your business?

                                    Meet with us! Schedule a meeting with us!