Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building RESTful Web services with Go

You're reading from   Building RESTful Web services with Go Learn how to build powerful RESTful APIs with Golang that scale gracefully

Arrow left icon
Product type Paperback
Published in Dec 2017
Publisher Packt
ISBN-13 9781788294287
Length 316 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Naren Yellavula Naren Yellavula
Author Profile Icon Naren Yellavula
Naren Yellavula
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Getting Started with REST API Development FREE CHAPTER 2. Handling Routing for Our REST Services 3. Working with Middleware and RPC 4. Simplifying RESTful Services with Popular Go Frameworks 5. Working with MongoDB and Go to Create REST APIs 6. Working with Protocol Buffers and GRPC 7. Working with PostgreSQL, JSON, and Go 8. Building a REST API Client in Go and Unit Testing 9. Scaling Our REST API Using Microservices 10. Deploying Our REST services 11. Using an API Gateway to Monitor and Metricize REST API 12. Handling Authentication for Our REST Services

REST verbs and status codes

REST verbs specify an action to be performed on a specific resource or a collection of resources. When a request is made by the client, it should send this information in the HTTP request:

  • REST verb
  • Header information
  • Body (optional)

As we mentioned previously, REST uses the URI to decode its resource to be handled. There are quite a few REST verbs available, but six of them are used frequently. They are as follows:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS

If you are a software developer, you will be dealing with these six most of the time. The following table explains the operation, target resource, and what happens if the request succeeds or fails:

REST Verb Action Success Failure
GET Fetches a record or set of resources from the server 200 404
OPTIONS Fetches all available REST operations  200 -
POST Creates a new set of resources or a resource 201 404, 409
PUT Updates or replaces the given record 200, 204 404
PATCH Modifies the given record 200, 204 404
DELETE Deletes the given resource  200 404

 

The numbers in the Success and Failure columns of the preceding table are HTTP status codes. Whenever a client initiates a REST operation, since REST is stateless, the client should know a way to find out whether the operation was successful or not. For that reason, HTTP has status codes for the response. REST defines the preceding status code types for a given operation. This means a REST API should strictly follow the preceding rules to achieve client-server communication.

All defined REST services have the following format. It consists of the host and API endpoint. The API endpoint is the URL path which is predefined by the server. Every REST request should hit that path.

A trivial REST API URI: http://HostName/API endpoint/Query(optional)

Let us look at all the verbs in more detail. The REST API design starts with the defining of operations and API endpoints. Before implementing the API, the design document should list all the endpoints for the given resources. In the following section, we carefully observe the REST API endpoints using PayPal's REST API as a use case.

GET

A GET method fetches the given resource from the server. To specify a resource, GET uses a few types of URI queries:

  • Query parameters
  • Path-based parameters

In case you didn't know, all of your browsing of the web is done by performing a GET request to the server. For example, if you type www.google.com, you are actually making a GET request to fetch the search page. Here, your browser is the client and Google's web server is the backend implementer of web services. A successful GET operation returns a 200 status code.

Examples of path parameters:

Everyone knows PayPal. PayPal creates billing agreements with companies. If you register with PayPal for a payment system, they provide you with a REST API for all your billing needs. The sample GET request for getting the information of a billing agreement looks like this: /v1/payments/billing-agreements/agreement_id.

Here, the resource query is with the path parameter. When the server sees this line, it interprets it as I got an HTTP request with a need for agreement_id from the billing agreements. Then it searches through the database, goes to the billing-agreements table, and finds an agreement with the given agreement_id. If that resource exists it sends the details to copy back in response (200 OK). Or else it sends a response saying resource not found (404).

Using GET, you can also query a list of resources, instead of a single one like the preceding example. PayPal's API for getting billing transactions related to an agreement can be fetched with /v1/payments/billing-agreements/transactions. This line fetches all transactions that occurred on that billing agreement. In both, the case's data is retrieved in the form of a JSON response. The response format should be designed beforehand so that the client can consume it in the agreement.

Examples of query parameters are as follows:

  • Query parameters are intended to add detailed information to identify a resource from the server. For example, take this sample fictitious API. Let us assume this API is created for fetching, creating, and updating the details of the book. A query parameter based GET request will be in this format: 
      /v1/books/?category=fiction&publish_date=2017
  • The preceding URI has few query parameters. The URI is requesting a book from the book's resource that satisfies the following conditions:
    • It should be a fiction book
    • The book should have been published in the year 2017

Get all the fiction books that are released in the year 2017 is the question the client is posing to the server. 

Path vs Query parameters—When to use them? It is a common rule of thumb that Query parameters are used to fetch multiple resources based on the query parameters. If a client needs a single resource with exact URI information, it can use Path parameters to specify the resource. For example, a user dashboard can be requested with Path parameters and fetch data on filtering can be modeled with Query parameters.

Use Path parameters for a single resource and Query parameters for multiple resources in a GET request.

POST, PUT, and PATCH 

The POST method is used to create a resource on the server. In the previous book's API, this operation creates a new book with the given details. A successful POST operation returns a 201 status code. The POST request can update multiple resources: /v1/books.

The POST request has a body like this: 

{"name" : "Lord of the rings", "year": 1954, "author" : "J. R. R. Tolkien"}

This actually creates a new book in the database. An ID is assigned to this record so that when we GET the resource, the URL is created. So POST should be done only once, in the beginning. In fact, Lord of the Rings was published in 1955. So we entered the published date incorrectly. In order to update the resource, let us use the PUT request.

The PUT method is similar to POST. It is used to replace the resource that already exists. The main difference is that PUT is idempotent. A POST call creates two instances with the same data. But PUT updates a single resource that already exists:

/v1/books/1256

with body that is JSON like this:

{"name" : "Lord of the rings", "year": 1955, "author" : "J. R. R. Tolkien"}

1256 is the ID of the book. It updates the preceding book by year:1955. Did you observe the drawback of PUT? It actually replaced the entire old record with the new one. We needed to change a single column. But PUT replaced the whole record. That is bad. For this reason, the PATCH request was introduced. 

The PATCH method is similar to PUT, except it won't replace the whole record. PATCH, as the name suggests, patches the column that is being modified. Let us update the book 1256 with a new column called ISBN:

/v1/books/1256

with the JSON body like this:

{"isbn" : "0618640150"}

It tells the server, Search for the book with id 1256. Then add/modify this column with the given value.

 PUT and PATCH both return the 200 status for success and 404 for not found.

DELETE and OPTIONS

The DELETE API method is used to delete a resource from the database. It is similar to PUT but without any body. It just needs an ID of the resource to be deleted. Once a resource gets deleted, subsequent GET requests return a 404 not found status. 

Responses to this method are not cacheable (in case caching is implemented)  because the DELETE method is idempotent.

The OPTIONS API method is the most underrated in the API development. Given the resource, this method tries to know all possible methods (GET, POST, and so on) defined on the server. It is like looking at the menu card at a restaurant and then ordering an item which is available (whereas if you randomly order a dish, the waiter will tell you it is not available). It is best practice to implement the OPTIONS method on the server. From the client, make sure OPTIONS is called first, and if the method is available, then proceed with it. 

Cross-Origin Resource Sharing (CORS)

The most important application of this OPTIONS method is Cross-Origin Resource Sharing (CORS). Initially, browser security prevented the client from making cross-origin requests. It means a site loaded with the URL www.foo.com can only make API calls to that host. If the client code needs to request files or data from www.bar.com, then the second server, bar.com, should have a mechanism to recognize foo.com to get its resources.

This process explains the CORS:

  1. foo.com requests the OPTIONS method on bar.com.
  2. bar.com sends a header like Access-Control-Allow-Origin: http://foo.com in response to the client.
  3. Next, foo.com can access the resources on bar.com without any restrictions that call any REST method.

If bar.com feels like supplying resources to any host after one initial request, it can set Access control to * (that is, any).

The following is the diagram depicting the process happening one after the other:

 

Types of status codes

There are a few families of status codes. Each family globally explains an operation status. Each member of that family may have a deeper meeting. So a REST API should strictly tell the client what exactly happened after the operation. There are 60+ status codes available. But for REST, we concentrate on a few families of codes.

2xx family (successful)

200 and 201 fall under the success family. They indicate that an operation was successful. Plain 200 (Operation Successful) is a successful CRUD Operation:

  • 200 (Successful Operation) is the most common type of response status code in REST
  • 201 (Successfully Created) is returned when a POST operation successfully creates a resource on the server
  • 204 (No content) is issued when a client needs a status but not any data back

3xx family (redirection)

These status codes are used to convey redirection messages. The most important ones are 301 and 304:  

  • 301 is issued when a resource is moved permanently to a new URL endpoint. It is essential when an old API is deprecated. It returns the new endpoint in the response with the 301 status. By seeing that, the client should use the new URL in response to achieving its target.
  • The 304 status code indicates that content is cached and no modification happened for the resource on the server. This helps in caching content at the client and only requests data when the cache is modified. 

4xx family (client error)

These are the standard error status codes which the client needs to interpret and handle further actions. These have nothing to do with the server. A wrong request format or ill-formed REST method can cause these errors. Of these, the most frequent status codes API developers use are 400, 401, 403, 404, and 405:

  • 400 (Bad Request) is returned when the server cannot understand the client request.
  • 401 (Unauthorized) is returned when the client is not sending the authorization information in the header.
  • 403 (Forbidden) is returned when the client has no access to a certain type of resources.
  • 404 (Not Found) is returned when the client request is on a resource that is nonexisting.
  • 405 (Method Not Allowed) is returned if the server bans a few methods on resources. GET and HEAD are exceptions.

5xx family (server error)

These are the errors from the server. The client request may be perfect, but due to a bug in the server code, these errors can arise. The commonly used status codes are 500, 501, 502, 503,  and 504:

  • 500 (Internal Server Error) status code gives the development error which is caused by some buggy code or some unexpected condition
  • 501 (Not Implemented) is returned when the server is no longer supporting the method on a resource
  • 502 (Bad Gateway) is returned when the server itself got an error response from another service vendor
  • 503 (Service Unavailable) is returned when the server is down due to multiple reasons, like a heavy load or for maintenance
  • 504 (Gateway Timeout) is returned when the server is waiting a long time for a response from another vendor and is taking too much time to serve the client

For more details on status codes, visit this link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

You have been reading a chapter from
Building RESTful Web services with Go
Published in: Dec 2017
Publisher: Packt
ISBN-13: 9781788294287
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime