REST API Design Basics

API ~ 8 minutes

# What is a REST API?

Hello and welcome! In this tutorial, we will learn how to design a clean REST API. An API is a door that lets one program talk to another program. For example, your mobile app talks to your server through an API.

REST is a set of simple rules for building such a door. It uses normal web tools, such as URLs, HTTP methods and JSON. Because the rules are simple, many developers can understand your API quickly.

The most important idea in REST is the resource. A resource is a thing in your system, like a user, a product or an order. Each resource gets its own URL. Then we use HTTP methods to say what we want to do with it.

What you will learn

  • How to name your URLs in a clean way
  • How to use the HTTP methods
  • How to send the right status codes
  • How to handle errors, pages and versions

Let us start with the names of the URLs.

Bad and good URLs
Code Copied to Clipboard

# Use nouns, not verbs

Please look at the example above. In the bad list, the URL contains a verb, such as get or delete. In the good list, the URL is only a noun, and the HTTP method tells us the action.

This gives us a very small and neat set of URLs. We use the plural word products for the collection. We add the id, like /products/5, for one single item.

Simple naming rules

  • Use small letters only
  • Use plural nouns, such as /users and /orders
  • Use hyphens for long names, such as /order-items
  • Show a link between things like this: /users/3/orders
  • Do not put file endings like .php in the URL

When all your URLs follow the same style, other developers can guess them without reading the manual.

Now let us talk about the HTTP methods. Each one has a clear meaning.

Main methods

  • GET reads data and never changes anything
  • POST creates a new resource
  • PUT replaces a resource fully
  • PATCH changes only some fields of a resource
  • DELETE removes a resource

A good rule is that GET must be safe. It must never change data. Why? Because browsers, search tools and caches may call GET URLs many times without asking you.

In Laravel, one line of code can make all these routes for you. Let us see it in the next block.

Resource routes in Laravel
Code Copied to Clipboard

# Check the routes

That one line made five routes for us. They are index, store, show, update and destroy. They match the table of HTTP methods we just learned.

If you do not use Laravel, do not worry. The ideas are the same in every language. Only the syntax is different.

To see the routes that Laravel made, please run the command below. It prints a table with the method, the URL and the controller of each route. This is a very good habit, because you can check your API design at a glance.

List all API routes
Code Copied to Clipboard

# Send correct status codes

Every answer from the server has a status code. It is a number that tells the client what happened. A good API always sends the right code. The client app can then decide what to do without reading the message.

Codes you will use often

  • 200 OK means the request worked
  • 201 Created means a new resource was made
  • 204 No Content means success, with nothing to return
  • 400 Bad Request means the request was wrong
  • 401 Unauthorized means the user must log in
  • 403 Forbidden means the user is not allowed
  • 404 Not Found means the resource does not exist
  • 422 Unprocessable Entity means validation failed
  • 500 Server Error means a bug on the server

The first digit gives a hint. The 2xx codes are good, the 4xx codes are the client's mistake, and the 5xx codes are the server's mistake.

A good success response
Code Copied to Clipboard

Wrap your data

Notice that we put the product inside a key called data. This is a small habit with a big benefit. Later, you may want to add extra information, such as page numbers or links. If your answer is a plain list, you cannot add them without breaking old clients.

Laravel has API Resources that do this wrapping for you. They also let you choose which fields to show. For example, you can hide the password field and show only the safe ones.

# Design clear errors

Errors will happen. A user may send a wrong value, or ask for an item that does not exist. A good API explains the problem in a clear and polite way.

Please use the same shape for all errors. Then the client app needs only one piece of code to show them. A short message for people, and a list of field errors for forms, are usually enough.

Laravel does this for you when validation fails. It returns the status code 422 with a JSON body like the one below. You only need to send the header Accept: application/json.

A validation error
Code Copied to Clipboard

# Pagination and filtering

Imagine you have one million products. If a client asks for GET /products, you cannot send them all at once. The server would be slow, and the phone would run out of memory.

The answer is pagination. We send the data in small pages. The client asks for a page with the query string, for example ?page=2&per_page=10. We can also let clients filter and sort, such as ?category=books&sort=price.

In Laravel, you only need to call paginate(10) instead of get(). Laravel reads the page value and adds the links and totals to the answer. Let us test it with curl.

Request page two
Code Copied to Clipboard

# Plan for versions

One day you will want to change your API. Maybe you will rename a field or remove one. But your old mobile apps are still in people's pockets, and they expect the old shape. If you break them, users will be unhappy.

The usual fix is versioning. You put the version in the URL, such as /api/v1/products. When you make big changes, you publish /api/v2/products, and you keep v1 alive for some time.

You can do this in Laravel with a route group and a prefix.

A versioned route group
Code Copied to Clipboard
Good API habits

Please remember these important habits. They make your API safe and friendly.

Checklist before you launch

  • Use HTTPS everywhere, never plain HTTP
  • Protect private routes with a token, for example with Sanctum
  • Validate every input on the server, even if the app checks it too
  • Limit the number of requests with rate limiting
  • Never return secret fields, such as passwords
  • Write down your API in a clear document

A tool like OpenAPI can help you describe your API in a standard way. Good documents save hours of questions from other developers.

# Create a resource with curl

Let us finish with one more test. We will create a product with a POST request. We send the data as JSON, so we need the header Content-Type: application/json. We also keep the Accept header.

If your route needs a login, please add the Authorization: Bearer YOUR_TOKEN header too. If all goes well, you should see the status 201 and the new product in the answer.

If you see 422, read the error list. It will tell you which field is wrong. This is exactly why we designed clear errors.

Create a product
Code Copied to Clipboard

# Summary and next steps

Great job! You now know the basics of a clean REST API. Let us review what we learned.

Summary

  • Resources are nouns, and URLs are plural and lower case
  • HTTP methods say the action: GET, POST, PUT, PATCH, DELETE
  • Status codes tell the client what happened
  • Errors and answers should always have the same shape
  • Pagination, filtering and versions keep your API ready for growth

What to learn next

  • Authentication with Laravel Sanctum
  • API Resources and transformers
  • Writing automated tests for each endpoint

You can read more about HTTP on MDN Web Docs. Thank you for learning with us!