0
0
Rest-apiHow-ToBeginner ยท 3 min read

How to Design REST API URLs: Best Practices and Examples

Design REST API URLs using clear, simple resource names in plural form, organized hierarchically with slashes /. Use HTTP methods like GET, POST, PUT, and DELETE to define actions, keeping URLs consistent and easy to understand.
๐Ÿ“

Syntax

A REST API URL typically follows this pattern:

  • https://api.example.com/ - Base URL
  • /resources - Plural noun representing the resource collection
  • /{id} - Optional identifier for a specific resource
  • ?query=params - Optional query parameters for filtering or pagination

HTTP methods define the action on the resource: GET to read, POST to create, PUT to update, and DELETE to remove.

http
GET /books          # List all books
GET /books/123      # Get book with ID 123
POST /books         # Create a new book
PUT /books/123      # Update book with ID 123
DELETE /books/123   # Delete book with ID 123
๐Ÿ’ป

Example

This example shows a simple REST API URL design for managing users and their posts.

http
GET /users           # List all users
GET /users/45        # Get user with ID 45
GET /users/45/posts  # List posts of user 45
POST /users          # Create a new user
PUT /users/45        # Update user 45
DELETE /users/45     # Delete user 45
Output
Response for GET /users: [ {"id": 45, "name": "Alice"}, {"id": 46, "name": "Bob"} ] Response for GET /users/45/posts: [ {"id": 101, "title": "Hello World"}, {"id": 102, "title": "REST API Tips"} ]
โš ๏ธ

Common Pitfalls

Common mistakes when designing REST API URLs include:

  • Using verbs in URLs like /getUser instead of HTTP methods.
  • Using singular resource names instead of plural.
  • Mixing actions and resources in the URL.
  • Not keeping URLs consistent and predictable.

Correct design uses nouns for resources and HTTP methods for actions.

http
Wrong:
GET /getUser/45
POST /createUser

Right:
GET /users/45
POST /users
๐Ÿ“Š

Quick Reference

Design PrincipleExampleNotes
Use plural nouns/booksRepresents collection of resources
Use HTTP methodsGET /booksDefines action on resource
Use hierarchical URLs/users/45/postsShows relationship between resources
Avoid verbs in URLsPOST /usersActions come from HTTP methods
Use query parameters/books?author=JohnFilter or paginate results
โœ…

Key Takeaways

Use plural nouns for resource names in URLs to represent collections.
Use HTTP methods (GET, POST, PUT, DELETE) to specify actions, not verbs in URLs.
Organize URLs hierarchically to show relationships between resources.
Keep URLs simple, consistent, and predictable for easy use.
Use query parameters for filtering, sorting, or pagination.