search
HomeDevelopment ToolsVSCodeDetailed explanation of how to use VSCode REST plug-in to make API calls

Detailed explanation of how to use VSCode REST plug-in to make API calls

Related recommendations: "vscode Basic Usage Tutorial"

Why should you leave the IDE to test new APIs? Now you don't have to.

How we get data

If you have been doing web development for a long time, you probably know that a lot of our work revolves around data of: reading data, writing data, manipulating data, and displaying it in the browser in a reasonable way.

Most of this data is provided by REST API endpoints. In layman's terms: the data we want exists in other services or databases, and our application queries the service to retrieve the data, and Use the data according to your own needs.

In the past, in order to test a REST API before connecting to the UI to accept data, you usually had to query the API through the command line of the terminal, or use a GUI like Insomnia or Postman (I wrote about them in a previous blog comparison).

But now, if you use VS Code (why not, it’s so great to write code with it!), life becomes simple. We no longer need to exit the IDE to test the API, because there is now a plugin that can do this: REST Client.

Using REST Client is very simple, I will show you how simple this plugin is and full-featured.

Get to know the VS Code REST Client plug-in

I am a fan of the VS Code code editor for several years. Every time I learn that someone has created a new I would be extremely grateful for any useful plugins and additions to the VS Code Marketplace.

So when I decided that it would be a pain to start Postman or Insomnia every time I needed to test a new API route, I discovered the REST Client plugin, which makes it easy. necessary.

REST Client is the most obvious name for a tool that exists to date, and its VS Code marketplace description accurately summarizes its capabilities: "REST Client allows you to send HTTP requests and view the responses directly in Visual Studio Code."

It's that simple. Then it gives a lot of details and examples of how to use it, but really, it's an HTTP tool built into VS Code. So let's start using it.

Install REST Client

To find it, open the Market extension in VS Code (the little Tetris icon on the left panel), enter " rest client" and install the first result in the list (the author should be Huachao Mao).

Detailed explanation of how to use VSCode REST plug-in to make API calls

After the installation is complete, we can continue with the settings.

Set up the REST Client script

Just create a file ending with .http in the root directory of the project, which the REST Client can recognize This, and knowing that it should be able to run HTTP requests from that file.

When testing, I took a dockerized full-stack MERN login application I made a few years ago and dropped a file I named test.http into the project folder. Root directory.

Detailed explanation of how to use VSCode REST plug-in to make API calls

Test it: Basic Operation

Here’s the cool part: In my experience, this little REST The Client plugin can do as much as more complex API clients like Postman.

Below, I'll show you how to do each type of basic CRUD operation, plus how to make API calls that require authentication like JWT tokens, using my MERN user registration application running locally to point to the call.

POST Example

The first example I will cover is the REST Client's POST because the user in my application must first You need to register to do anything else (after all, this is just a login service).

Therefore, this code will be displayed in the test.http file.

Detailed explanation of how to use VSCode REST plug-in to make API calls

Okay, let’s review what’s happening in the above code snippet.

The first thing a REST Client needs in order to work properly is the type of request being made and the full URL path of the route it is trying to access. In this case, the request is POST and the URL is http://localhost:3003/registerUser. The HTTP/1.1 at the end of the first line relates to the standard established by RFC 2616, but I'm not sure if it's necessary, so I'm leaving it in just to be safe.

Then, because this is a POST, a JSON body must be included in the request, paying attention between Content-Type and body There is a blank line - this is intentionally required by the REST Client. So, we fill in the required fields, and then a small send Request option should appear above POST. Put your mouse over it and click to see what happens.

Detailed explanation of how to use VSCode REST plug-in to make API calls

The last thing you want to pay attention to is the after the request in the test.http file, which is the delimiter between requests , you can include any number of requests in the file by inserting

between each request.

If the request is successful, you will see something similar to what I posted above. Even if the request is unsuccessful, you still get all this information about what just happened and (hopefully) what went wrong. Cool

GET Example

Now a user has been created, let’s say we forgot their password and they sent an email to retrieve it. The email contains a token and a link that will take them to a page to reset their password. Once they click the link and land on the page, a

GET

request is initiated to ensure that the token included in the email to reset their password is valid, and that's it possible. Detailed explanation of how to use VSCode REST plug-in to make API calls

My GET points to the /reset endpoint and appends the resetPasswordToken required for authentication on the server side Query parameters. Content-Type is still application/json, and the

at the bottom separates this request from any other requests in the file.

Detailed explanation of how to use VSCode REST plug-in to make API calls If the token is indeed valid, the server's response will look like this:

And that's all the GET request requires, they don't have to worry about the request body problem.

Update Example

Detailed explanation of how to use VSCode REST plug-in to make API callsNext is U: Update in CRUD. Let's say a user wants to update something in their profile information. Using REST Client is not difficult either.

For this request, the request type is updated to

PUT

, and the body includes any fields on the object that need to be updated. In my application, users can update their first name, last name, or email.

Detailed explanation of how to use VSCode REST plug-in to make API callsSo, when passing the body, this is what the Response tab in VS Code will look like if the REST Client successfully hits the PUT endpoint.

That’s it, let’s move on to the authentication example. Because as far as I know there are very few applications without protected routing that require some kind of authentication.

Authentication Example

Once again I was impressed by the breadth of different authentication formats supported by REST Client. As of this writing, the REST Client's documentation says it supports six popular authentication types, including support for JWT authentication, which is the authentication type my application relies on on all protected routes.

Detailed explanation of how to use VSCode REST plug-in to make API callsSo without further ado, here is one of the endpoints I need to validate: looking up the user's information in the database.

Adding authorization in a REST Client request is really simple: simply add the key Authorization

below where the route and content-type are declared, Then (at least for my case) I add the JWT's keys and values ​​(as they appear in the browser's local storage) as the values ​​of the

Authorization

header.

This becomes:

Authorization: jwt XXXXXXXXXXXXXXXXXX
Then just send the request and see what happens.

If your authentication is configured correctly, you will receive some type of 200 response from the server, which for my request will return all the information stored in the database related to that user, and A message that the user was successfully found.

This part may take some trial and error, but if you can figure out how a successful request is made in the browser's Dev Tools network call, through an existing Swagger endpoint, or through something else like documentation, it's well worth it.

DELETE Example

Detailed explanation of how to use VSCode REST plug-in to make API callsAfter the other examples I provided above, this example should be simple

ThisDELETE

The required query parameter is

username1Detailed explanation of how to use VSCode REST plug-in to make API calls, so that it knows which user in the database to delete, and it also needs to verify whether this user is qualified to make this request. Other than that, there's nothing new to introduce here.

#########

На самом деле это лишь верхушка айсберга того, что может сделать клиент REST. Я рассмотрел запросы REST и одну форму аутентификации, но он также может поддерживать запросы GraphQL, несколько других типов аутентификации, переменные среды и пользовательские переменные, просмотр и сохранение необработанных ответов и многое другое.

Я настоятельно рекомендую вам ознакомиться с документацией, чтобы понять все возможности клиента REST, он очень мощный.

Документация клиента REST: https://blog.bitsrc.io/vs-codes-rest-client-plugin-is-all-you-need-to-make-api-calls-e9e95fcfd85a

End

Данные управляют Интернетом, и по мере дальнейшего продвижения по карьерной лестнице веб-разработчики со временем становятся очень хорошими в доступе к данным и их преобразовании для удовлетворения ваших потребностей. собственные нужды.

Раньше, получая данные, размещенные в другом месте, веб-разработчики часто обращались к таким инструментам, как Postman или Insomnia, чтобы иметь немного лучший интерфейс, чем командная строка, но теперь есть плагин VS Code, который делает необходимым код редакторы ушли в прошлое, это называется REST Client, и это здорово.

операция CRUD? без проблем! Поддержка GraphQL? без проблем! Варианты аутентификации? без проблем! Клиент REST предоставляет все эти и многие другие возможности и очень прост в настройке и использовании. Я определенно буду использовать его больше в будущих проектах.

Пожалуйста, зайдите сюда через несколько недель – я буду писать больше о JavaScript, React, ES6 и обо всем, что связано с веб-разработкой.

Спасибо за чтение. Я надеюсь, что вы рассмотрите возможность использования клиента REST для обработки любых запросов API, которые могут вам понадобиться в будущем. Я думаю, вы будете приятно удивлены тем приятным опытом, который он может предоставить без необходимости использования какого-либо графического интерфейса API.

Оригинальный адрес: https://blog.bitsrc.io/

Автор: Paige Niedringhaus

Адрес перевода: https://segmentfault.com/a /1190000038223490

Для получения дополнительной информации о программировании посетите: Курс обучения программированию! !

The above is the detailed content of Detailed explanation of how to use VSCode REST plug-in to make API calls. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Choosing Between Visual Studio and VS Code: The Right Tool for YouChoosing Between Visual Studio and VS Code: The Right Tool for YouMay 09, 2025 am 12:21 AM

VisualStudio is suitable for large projects, VSCode is suitable for projects of all sizes. 1. VisualStudio provides comprehensive IDE functions, supports multiple languages, integrated debugging and testing tools. 2.VSCode is a lightweight editor that supports multiple languages ​​through extension, has a simple interface and fast startup.

Visual Studio: A Powerful Tool for DevelopersVisual Studio: A Powerful Tool for DevelopersMay 08, 2025 am 12:19 AM

VisualStudio is a powerful IDE developed by Microsoft, supporting multiple programming languages ​​and platforms. Its core advantages include: 1. Intelligent code prompts and debugging functions, 2. Integrated development, debugging, testing and version control, 3. Extended functions through plug-ins, 4. Provide performance optimization and best practice tools to help developers improve efficiency and code quality.

Visual Studio vs. VS Code: Pricing, Licensing, and AvailabilityVisual Studio vs. VS Code: Pricing, Licensing, and AvailabilityMay 07, 2025 am 12:11 AM

The differences in pricing, licensing and availability of VisualStudio and VSCode are as follows: 1. Pricing: VSCode is completely free, while VisualStudio offers free community and paid enterprise versions. 2. License: VSCode uses a flexible MIT license, and the license of VisualStudio varies according to the version. 3. Usability: VSCode is supported across platforms, while VisualStudio performs best on Windows.

Visual Studio: From Code to ProductionVisual Studio: From Code to ProductionMay 06, 2025 am 12:10 AM

VisualStudio supports the entire process from code writing to production deployment. 1) Code writing: Provides intelligent code completion and reconstruction functions. 2) Debugging and testing: Integrate powerful debugging tools and unit testing framework. 3) Version control: seamlessly integrate with Git to simplify code management. 4) Deployment and Release: Supports multiple deployment options to simplify the application release process.

Visual Studio: A Look at the Licensing LandscapeVisual Studio: A Look at the Licensing LandscapeMay 05, 2025 am 12:17 AM

VisualStudio offers three license types: Community, Professional and Enterprise. The Community Edition is free, suitable for individual developers and small teams; the Professional Edition is annually subscribed, suitable for professional developers who need more functions; the Enterprise Edition is the highest price, suitable for large teams and enterprises. When selecting a license, project size, budget and teamwork needs should be considered.

The Ultimate Showdown: Visual Studio vs. VS CodeThe Ultimate Showdown: Visual Studio vs. VS CodeMay 04, 2025 am 12:01 AM

VisualStudio is suitable for large-scale project development, while VSCode is suitable for projects of all sizes. 1. VisualStudio provides comprehensive development tools, such as integrated debugger, version control and testing tools. 2.VSCode is known for its scalability, cross-platform and fast launch, and is suitable for fast editing and small project development.

Visual Studio vs. VS Code: Comparing the Two IDEsVisual Studio vs. VS Code: Comparing the Two IDEsMay 03, 2025 am 12:04 AM

VisualStudio is suitable for large projects and Windows development, while VSCode is suitable for cross-platform and small projects. 1. VisualStudio provides a full-featured IDE, supports .NET framework and powerful debugging tools. 2.VSCode is a lightweight editor that emphasizes flexibility and extensibility, and is suitable for various development scenarios.

Visual Studio: Comparing Free and Paid OptionsVisual Studio: Comparing Free and Paid OptionsMay 02, 2025 am 12:09 AM

When choosing VisualStudio, the free version is suitable for individual developers and small teams, and the paid version is suitable for large enterprises and users who need advanced features. 1. The free CommunityEdition provides basic development tools for individuals and small teams. 2. Paid Professional and Enterprise Editions provide advanced features and support for business environments and large teams.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!