HTTP Methods in REST: What They Are and How They Work
HTTP methods are actions that tell the server what to do with a resource, such as GET to retrieve data, POST to create data, PUT to update data, and DELETE to remove data. These methods define how clients interact with the server in a simple and standardized way.How It Works
Think of HTTP methods as instructions you give to a waiter in a restaurant. You can ask to see the menu (GET), place an order (POST), change your order (PUT), or cancel it (DELETE). In REST APIs, these methods tell the server what action to perform on the data.
Each method has a clear purpose: GET fetches information without changing anything, POST adds new information, PUT replaces existing information, and DELETE removes information. This makes communication between client and server simple and predictable.
Example
This example shows how to use HTTP methods with a simple REST API for managing books.
import requests url = 'https://example.com/api/books' # GET: Retrieve list of books response_get = requests.get(url) print('GET status:', response_get.status_code) print('GET data:', response_get.json()) # POST: Add a new book new_book = {'title': 'Learn REST', 'author': 'Jane Doe'} response_post = requests.post(url, json=new_book) print('POST status:', response_post.status_code) print('POST data:', response_post.json()) # PUT: Update a book with id 1 update_book = {'title': 'Learn REST - Updated', 'author': 'Jane Doe'} response_put = requests.put(f'{url}/1', json=update_book) print('PUT status:', response_put.status_code) # DELETE: Remove a book with id 1 response_delete = requests.delete(f'{url}/1') print('DELETE status:', response_delete.status_code)
When to Use
Use GET when you want to read or fetch data without changing it, like viewing a profile or list of items. Use POST to create new data, such as submitting a form or adding a new record. Use PUT to update or replace existing data, for example, editing a user's details. Use DELETE to remove data, like deleting a comment or account.
These methods help keep your API clear and organized, making it easier for developers to understand and use your service correctly.
Key Points
- GET retrieves data without changing it.
- POST creates new data on the server.
- PUT updates or replaces existing data.
- DELETE removes data from the server.
- HTTP methods make REST APIs simple and predictable.