0
0
Rest APIprogramming~5 mins

Authentication documentation in Rest API

Choose your learning style9 modes available
Introduction

Authentication helps confirm who you are when using an app or website. It keeps your information safe by making sure only you can access your account.

When users need to log in to access their personal data.
When an app needs to protect sensitive information from strangers.
When you want to track who is using your service.
When you want to allow users to sign up and create accounts.
When you want to control access to certain parts of your API.
Syntax
Rest API
POST /login
Headers:
  Content-Type: application/json
Body:
  {
    "username": "user123",
    "password": "mypassword"
  }

Response:
  {
    "token": "abc123xyz",
    "expires_in": 3600
  }

The client sends a username and password to the server.

The server responds with a token that the client uses to prove identity on future requests.

Examples
User 'alice' sends her login details to get a token.
Rest API
POST /login
{
  "username": "alice",
  "password": "secret"
}
Client uses the token in the Authorization header to access protected data.
Rest API
GET /profile
Headers:
  Authorization: Bearer abc123xyz
User logs out by telling the server to invalidate the token.
Rest API
POST /logout
Headers:
  Authorization: Bearer abc123xyz
Sample Program

This program logs in a user, gets a token, then uses that token to request the user's profile data.

Rest API
import requests

# User logs in
login_url = 'https://example.com/api/login'
credentials = {'username': 'bob', 'password': 'mypassword'}
response = requests.post(login_url, json=credentials)

if response.status_code == 200:
    token = response.json().get('token')
    print(f'Login successful. Token: {token}')

    # Use token to get profile
    profile_url = 'https://example.com/api/profile'
    headers = {'Authorization': f'Bearer {token}'}
    profile_response = requests.get(profile_url, headers=headers)

    if profile_response.status_code == 200:
        print('Profile data:', profile_response.json())
    else:
        print('Failed to get profile')
else:
    print('Login failed')
OutputSuccess
Important Notes

Always use HTTPS to keep login details safe.

Tokens usually expire after some time for security.

Store tokens securely on the client side, like in memory or secure storage.

Summary

Authentication confirms who a user is.

Clients send login info and get a token to prove identity.

Tokens are used in headers to access protected API parts.