Skip to content

docs: Add API testing guide with Postman examples #970

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions v3/docs/references/testing-and-debugging/api-testing.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
---
title: API Testing
hide_title: true
sidebar_position: 1
description: >-
Test the APIs exposed by the backend SDK.
---

import { BackendTabs } from "/src/components/Tabs";

# Testing with postman

The following guide goes over the process of testing backend APIs with Postman. These APIs are automatically exposed via the backend SDK (`/auth/*` path).

:::info Important
- Make sure that the ThirdParty Recipe is correctly setup in your backend
- For the examples given below, the backend runs on domain `localhost` and port `3001`.
- You can find the Open API spec for the APIs under test [in the SwaggerHub API documentation](https://app.swaggerhub.com/apis/SuperTokens/FDI).
- Postman does cookie management on its own. You don't need to manually set cookies on each request.
:::

## 1. Sign up
The `/auth/signinup` API requires the `redirectURI`, `thirdPartyId`, and `code` attributes to appear as a JSON object in the request body.
- `redirectURI`: It is the link that redirects the user after authentication. For example, for sign in with Google, the value of this is `{websiteDomain}/auth/callback/google`.
- `thirdPartyId`: The id used to identify the provider. For example, if Google is a ThirdParty provider, its `thirdPartyId` is `google`.
- `code`: The auth code that the third party provider sends when they call the `redirectURI` (post auth from their UI).

- On a successful response, a new user session creates session tokens set in the response, and the response body contains the `user` object, the `createdNewUser`, and `status` values as JSON data.

- The following session tokens appear:
- `stAccessToken`
- `stRefreshToken`

- More information about these cookies is available [in the session management security documentation](/docs/post-authentication/session-management/security#cookie-consent).


## 2. Session verification

- You can also test APIs that require the user to log in.

- For example, there is an API used to query user data with the `verifySession` middleware as shown below.

<BackendTabs>
<BackendTabs.TabItem value="nodejs">

```tsx
import express from "express";
import { verifySession } from "supertokens-node/recipe/session/framework/express";

let app = express();

// The following code snippet is an example API. You do not need to
// implement it in your app

app.post("/change-user-data", verifySession(), async (req, res) => {
let userId = req.session.getUserId();
// mutate some user data
res.send({
userId
})
})
```

</BackendTabs.TabItem>
<BackendTabs.TabItem value="go">

```go
import (
"encoding/json"
"net/http"

"github.com/supertokens/supertokens-golang/recipe/session"
"github.com/supertokens/supertokens-golang/supertokens"
)

// The following code snippet is an example API. You do not need to
// implement it in your app

func main() {
http.ListenAndServe(":3001", supertokens.Middleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// Handle your APIs..

if r.URL.Path == "/change-user-data" {
session.VerifySession(nil, func(w http.ResponseWriter, r *http.Request) {
sessionContainer := session.GetSessionFromRequestContext(r.Context())

w.WriteHeader(200)
w.Header().Add("content-type", "application/json")
bytes, err := json.Marshal(map[string]interface{}{
"userId": sessionContainer.GetUserID(),
})
if err != nil {
w.WriteHeader(500)
w.Write([]byte("error in converting to json"))
} else {
w.Write(bytes)
}

}).ServeHTTP(rw, r)
return
}
})))
}
```

</BackendTabs.TabItem>
<BackendTabs.TabItem value="python">

```python
# The following code snippet is an example API (fastapi). You do not need to
# implement it in your app

from supertokens_python.recipe.session.framework.fastapi import verify_session
from supertokens_python.recipe.session import SessionContainer
from fastapi import Depends

@app.post('/change-user-data') # type: ignore
async def change_user_data(session: SessionContainer = Depends(verify_session())):
_ = session.get_user_id()
# mutate some user data
# send response
```

</BackendTabs.TabItem>
</BackendTabs>

- In Postman, set the request type to `POST`.
- Set the URL to `http://localhost:3001/change-user-data`
- If you have the `antiCsrf` attribute set to `VIA_TOKEN` in your backend SuperTokens configuration, then in the Postman Header tab, set a key as `anti-csrf` and value as the `anti-csrf` token retrieved from the login response.
- On a successful response, the response body contains user data.

:::info Important
By default, for `GET` APIs, you don't need to provide the `anti-csrf` request header as anti-CSRF checks are only done in non-`GET` APIs
:::

<img alt="Request to change user data in postman" width="600px" src="/img/st-thirdparty-change-user.png" />

In case you query the `/change-user-data` API with an expired access token, you receive a `401` response with the message `try refresh token`.

<img alt="Failed query due to expired access token in postman" width="600px" src="/img/emailpassword/st-user-unauthorized.png" />

To generate new session tokens you can use the `/auth/session/refresh` API as shown in the next section.


## 3. Refreshing session tokens

In case your `access token` expires you can call the `/auth/session/refresh` API to generate a new `access token` and `refresh token`.
- In Postman, set the request type to `POST`.
- Set the URL to `http://localhost:3001/auth/session/refresh`
- On a successful response, the system sets new session tokens.

<img alt="Successful session refresh in postman" width="600px" src="/img/emailpassword/st-ep-refresh.png" />

You can see the new session tokens by switching to the cookies tab

<img alt="Viewing session tokens in cookies tab in postman" width="600px" src="/img/emailpassword/st-ep-refresh-cookies.png" />


## 4. Logout

The `/auth/signout` API invalidates the user sessions. This clears the session cookies set in Postman.
- In Postman, set the request type to `POST`.
- Set the URL to `http://localhost:3001/auth/signout`
- On a successful response, Postman and the database clear the session tokens.

<img alt="Successful sign out request in postman" width="600px" src="/img/emailpassword/st-ep-signout.png" />