0
0
Rest APIprogramming~5 mins

Client-server architecture in Rest API

Choose your learning style9 modes available
Introduction

Client-server architecture helps computers talk to each other. One computer (server) gives information, and another (client) asks for it.

When you want a website to show data from a database.
When a mobile app needs to get information from the internet.
When multiple users share the same service, like email or chat.
When you want to separate the part that shows data from the part that stores data.
Syntax
Rest API
Client sends a request to Server
Server processes the request
Server sends back a response to Client
The client is usually a web browser or app.
The server waits and listens for requests from clients.
Examples
Client asks the server for a list of users.
Rest API
GET /users HTTP/1.1
Host: example.com
Client sends login details to the server.
Rest API
POST /login HTTP/1.1
Host: example.com
Content-Type: application/json

{"username":"user1", "password":"pass"}
Sample Program

This program creates a simple server using Flask. It has two parts:

  • One part sends a list of users when the client asks.
  • Another part greets the user by name when the client sends a name.

You can test it by sending requests from a client like a browser or Postman.

Rest API
from flask import Flask, jsonify, request

app = Flask(__name__)

users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/greet', methods=['POST'])
def greet_user():
    data = request.get_json()
    name = data.get('name', 'Guest')
    return jsonify({"message": f"Hello, {name}!"})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

The client and server communicate using requests and responses.

Servers can handle many clients at the same time.

Client-server helps keep things organized and secure.

Summary

Client-server architecture splits work between two computers.

Clients ask for data; servers send data back.

This setup is common in websites and apps.