0
0
Rest APIprogramming~5 mins

REST constraints and principles in Rest API

Choose your learning style9 modes available
Introduction

REST helps computers talk to each other in a simple and clear way. It makes web services easy to use and understand.

When building a web service that needs to be easy to use by many different apps.
When you want your service to be fast and reliable by using simple rules.
When you want to organize your data and actions clearly using web addresses.
When you want your service to work well on the internet with many users.
When you want to make your service easy to update and maintain over time.
Syntax
Rest API
REST uses these main rules:
1. Client-Server: Separate user interface and data storage.
2. Stateless: Each request has all info needed.
3. Cacheable: Responses can be stored to speed up.
4. Uniform Interface: Use standard ways to access resources.
5. Layered System: Use layers to organize the system.
6. Code on Demand (optional): Servers can send code to clients.

These rules help make web services simple and scalable.

Not all rules are always used, but most REST services follow many of them.

Examples
This shows the Uniform Interface and Stateless rules in action.
Rest API
GET /books/123

// Client asks server for book with ID 123 using a simple URL.
Shows how client-server and uniform interface work together.
Rest API
POST /books
{
  "title": "Learn REST",
  "author": "Jane"
}

// Client sends new book data to server to add it.
This is the Cacheable constraint helping speed up responses.
Rest API
Cache-Control: max-age=3600

// Server tells client it can save response for 1 hour.
Sample Program

This program asks a web service for a post using a simple URL. It shows stateless and uniform interface principles.

Rest API
import requests

# Simple example showing REST principles

# Stateless request: all info in URL
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

# Print response data
print(response.json())
OutputSuccess
Important Notes

Stateless means the server does not remember past requests from the client.

Uniform Interface means using standard HTTP methods like GET, POST, PUT, DELETE.

Cacheable responses help reduce network traffic and speed up apps.

Summary

REST uses simple rules to make web services easy and fast.

Key rules include statelessness, uniform interface, and caching.

Following REST helps apps work well on the internet and stay easy to maintain.