0
0
Rest APIprogramming~5 mins

Client credentials flow in Rest API

Choose your learning style9 modes available
Introduction

The client credentials flow lets a program get permission to access a service by proving who it is, without needing a user to log in.

When a backend service needs to talk to another service securely.
When an app needs to get data from an API without a user involved.
When automating tasks that require access to protected resources.
When a system component needs to authenticate itself to get tokens.
When you want to keep user data private and only use app identity.
Syntax
Rest API
POST /token HTTP/1.1
Host: authorization-server.com
Content-Type: application/x-www-form-urlencoded

client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials

The request is sent as a POST with form data.

You must include your client ID and secret to prove your app's identity.

Examples
This example shows how to request a token using your app's ID and secret.
Rest API
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

client_id=myapp123&client_secret=secret456&grant_type=client_credentials
Using curl command line tool to get an access token with client credentials flow.
Rest API
curl -X POST https://auth.example.com/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id=myapp123&client_secret=secret456&grant_type=client_credentials"
Sample Program

This Python program sends a POST request to get an access token using client credentials. It prints the token if successful.

Rest API
import requests

url = "https://auth.example.com/token"
data = {
    "client_id": "myapp123",
    "client_secret": "secret456",
    "grant_type": "client_credentials"
}

response = requests.post(url, data=data)

if response.status_code == 200:
    token_info = response.json()
    print(f"Access token: {token_info['access_token']}")
else:
    print(f"Failed to get token: {response.status_code}")
OutputSuccess
Important Notes

Keep your client secret safe and never share it publicly.

The access token you get usually expires after some time, so you may need to request a new one.

This flow does not involve user login, so it is good for server-to-server communication.

Summary

Client credentials flow lets apps get tokens by proving their identity.

It is used when no user is involved, like backend services talking to APIs.

You send your client ID and secret to get an access token.