Home >Development Tools >VSCode >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.
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.
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.
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).
After the installation is complete, we can continue with the settings.
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.
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.
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.
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.
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.
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
request is initiated to ensure that the token included in the email to reset their password is valid, and that's it possible.
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
If the token is indeed valid, the server's response will look like this:
Update Example
Next 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.
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.So, 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.
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.So 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
Authorization
header. This becomes:Authorization: jwt XXXXXXXXXXXXXXXXXXThen 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.
DELETE Example
After the other examples I provided above, this example should be simple
This
DELETE
username, 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
Данные управляют Интернетом, и по мере дальнейшего продвижения по карьерной лестнице веб-разработчики со временем становятся очень хорошими в доступе к данным и их преобразовании для удовлетворения ваших потребностей. собственные нужды.
Раньше, получая данные, размещенные в другом месте, веб-разработчики часто обращались к таким инструментам, как 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!