Professional Documents
Culture Documents
authentication methods, Design and deploy a cloud based web-service that uses the REST interface to
respond to queries that require running an analytics job on a large data set which is stored in a
database. The web-services are evaluated through a load generator for a fixed time period (several
hours) by measuring the cost of cloud resources used and their system’s performance (throughput).
RESTful API is an interface that two computer systems use to exchange information securely over the
internet. Most business applications have to communicate with other internal and third-party
applications to perform various tasks. For example, to generate monthly payslips, your internal
accounts system has to share data with your customer's banking system to automate invoicing and
communicate with an internal timesheet application. RESTful APIs support this information exchange
because they follow secure, reliable, and efficient software communication standards.
What is an API?
An application programming interface (API) defines the rules that you must follow to communicate
with other software systems. Developers expose or create APIs so that other applications can
communicate with their applications programmatically. For example, the timesheet application
exposes an API that asks for an employee's full name and a range of dates. When it receives this
information, it internally processes the employee's timesheet and returns the number of hours worked
in that date range.
You can think of a web API as a gateway between clients and resources on the web.
Clients
Clients are users who want to access information from the web. The client can be a person or a
software system that uses the API. For example, developers can write programs that access weather
data from a weather system. Or you can access the same data from your browser when you visit the
weather website directly.
Resources
Resources are the information that different applications provide to their clients. Resources can be
images, videos, text, numbers, or any type of data. The machine that gives the resource to the client is
also called the server. Organizations use APIs to share resources and provide web services while
maintaining security, control, and authentication. In addition, APIs help them to determine which
clients get access to specific internal resources.
What is REST?
Representational State Transfer (REST) is a software architecture that imposes conditions on how an
API should work. REST was initially created as a guideline to manage communication on a complex
network like the internet. You can use REST-based architecture to support high-performing and
reliable communication at scale. You can easily implement and modify it, bringing visibility and
cross-platform portability to any API system.
API developers can design APIs using several different architectures. APIs that follow the REST
architectural style are called REST APIs. Web services that implement REST architecture are called
RESTful web services. The term RESTful API generally refers to RESTful web APIs. However, you
can use the terms REST API and RESTful API interchangeably.
The following are some of the principles of the REST architectural style:
Uniform interface
The uniform interface is fundamental to the design of any RESTful webservice. It indicates that the
server transfers information in a standard format. The formatted resource is called a representation in
REST. This format can be different from the internal representation of the resource on the server
application. For example, the server can store data as text but send it in an HTML representation
format.
Uniform interface imposes four architectural constraints:
Clients have enough information in the resource representation to modify or delete the
resource if they want to. The server meets this condition by sending metadata that describes
the resource further.
Clients receive information about how to process the representation further. The server
achieves this by sending self-descriptive messages that contain metadata about how the client
can best use them.
Clients receive information about all other related resources they need to complete a task. The
server achieves this by sending hyperlinks in the representation so that clients can
dynamically discover more resources.
Statelessness: In REST architecture, statelessness refers to a communication method in which the
server completes every client request independently of all previous requests. Clients can request
resources in any order, and every request is stateless or isolated from other requests. This REST API
design constraint implies that the server can completely understand and fulfill the request every time.
Layered system: In a layered system architecture, the client can connect to other authorized
intermediaries between the client and server, and it will still receive responses from the server.
Servers can also pass on requests to other servers. You can design your RESTful web service to run
on several servers with multiple layers such as security, application, and business logic, working
together to fulfill client requests. These layers remain invisible to the client.
Cacheability: RESTful web services support caching, which is the process of storing some responses
on the client or on an intermediary to improve server response time. For example, suppose that you
visit a website that has common header and footer images on every page. Every time you visit a new
website page, the server must resend the same images. To avoid this, the client caches or stores these
images after the first response and then uses the images directly from the cache. RESTful web
services control caching by using API responses that define themselves as cacheable or noncacheable.
Code on demand: In REST architectural style, servers can temporarily extend or customize client
functionality by transferring software programming code to the client. For example, when you fill a
registration form on any website, your browser immediately highlights any mistakes you make, such
as incorrect phone numbers. It can do this because of the code sent by the server.
What are the benefits of RESTful APIs?
RESTful APIs include the following benefits:
Scalability: Systems that implement REST APIs can scale efficiently because REST optimizes client-
server interactions. Statelessness removes server load because the server does not have to retain past
client request information. Well-managed caching partially or completely eliminates some client-
server interactions. All these features support scalability without causing communication bottlenecks
that reduce performance.
Flexibility: RESTful web services support total client-server separation. They simplify and decouple
various server components so that each part can evolve independently. Platform or technology
changes at the server application do not affect the client application. The ability to layer application
functions increases flexibility even further. For example, developers can make changes to the database
layer without rewriting the application logic.
Independence: REST APIs are independent of the technology used. You can write both client and
server applications in various programming languages without affecting the API design. You can also
change the underlying technology on either side without affecting the communication.
How do RESTful APIs work?
The basic function of a RESTful API is the same as browsing the internet. The client contacts the
server by using the API when it requires a resource. API developers explain how the client should use
the REST API in the server application API documentation. These are the general steps for any REST
API call:
The client sends a request to the server. The client follows the API documentation to format
the request in a way that the server understands.
The server authenticates the client and confirms that the client has the right to make that
request.
The server returns a response to the client. The response contains information that tells the
client whether the request was successful. The response also includes any information that the
client requested.
The REST API request and response details vary slightly depending on how the API
developers design the API.
What does the RESTful API client request contain?
RESTful APIs require requests to contain the following main components:
Unique resource identifier: The server identifies each resource with unique resource identifiers. For
REST services, the server typically performs resource identification by using a Uniform Resource
Locator (URL). The URL specifies the path to the resource. A URL is similar to the website address
that you enter into your browser to visit any webpage. The URL is also called the request endpoint
and clearly specifies to the server what the client requires.
Method: Developers often implement RESTful APIs by using the Hypertext Transfer Protocol
(HTTP). An HTTP method tells the server what it needs to do to the resource. The following are four
common HTTP methods:
GET: Clients use GET to access resources that are located at the specified URL on the server. They
can cache GET requests and send parameters in the RESTful API request to instruct the server to filter
data before sending.
POST: Clients use POST to send data to the server. They include the data representation with the
request. Sending the same POST request multiple times has the side effect of creating the same
resource multiple times.
PUT: Clients use PUT to update existing resources on the server. Unlike POST, sending the same
PUT request multiple times in a RESTful web service gives the same result.
DELETE: Clients use the DELETE request to remove the resource. A DELETE request can change the
server state. However, if the user does not have appropriate authentication, the request fails.
HTTP headers: Request headers are the metadata exchanged between the client and server. For
instance, the request header indicates the format of the request and response, provides information
about request status, and so on.
Data: REST API requests might include data for the POST, PUT, and other HTTP methods to work
successfully.
Parameters: RESTful API requests can include parameters that give the server more details about what
needs to be done. The following are some different types of parameters:
Path parameters that specify URL details.
Query parameters that request more information about the resource.
Cookie parameters that authenticate clients quickly.
What are RESTful API authentication methods?
A RESTful web service must authenticate requests before it can send a response. Authentication is the
process of verifying an identity. For example, you can prove your identity by showing an ID card or
driver's license. Similarly, RESTful service clients must prove their identity to the server to establish
trust.
RESTful API has four common authentication methods:
HTTP authentication: HTTP defines some authentication schemes that you can use directly when you
are implementing REST API. The following are two of these schemes:
Basic authentication: In basic authentication, the client sends the user name and password in the request
header. It encodes them with base64, which is an encoding technique that converts the pair into a set
of 64 characters for safe transmission.
Bearer authentication: The term bearer authentication refers to the process of giving access control to
the token bearer. The bearer token is typically an encrypted string of characters that the server
generates in response to a login request. The client sends the token in the request headers to access
resources.
API keys: API keys are another option for REST API authentication. In this approach, the server
assigns a unique generated value to a first-time client. Whenever the client tries to access resources, it
uses the unique API key to verify itself. API keys are less secure because the client has to transmit the
key, which makes it vulnerable to network theft.
OAuth: OAuth combines passwords and tokens for highly secure login access to any system. The
server first requests a password and then asks for an additional token to complete the authorization
process. It can check the token at any time and also over time with a specific scope and longevity.
What does the RESTful API server response contain?
REST principles require the server response to contain the following main components:
Status line: The status line contains a three-digit status code that communicates request success or
failure. For instance, 2XX codes indicate success, but 4XX and 5XX codes indicate errors. 3XX codes
indicate URL redirection.
The following are some common status codes:
200: Generic success response
Prerequisites
An installation of Go 1.16 or later. For installation instructions, see Installing Go.
A tool to edit your code. Any text editor you have will work fine.
A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or
cmd in Windows.
The curl tool. On Linux and Mac, this should already be installed. On Windows, it’s included on
Windows 10 Insider build 17063 and later. For earlier Windows versions, you might need to install it.
For more, see Tar and Curl Come to Windows.
Design API endpoints
You’ll build an API that provides access to a store selling vintage recordings on vinyl. So you’ll need
to provide endpoints through which a client can get and add albums for users.
When developing an API, you typically begin by designing the endpoints. Your API’s users will have
more success if the endpoints are easy to understand.
Here are the endpoints you’ll create in this tutorial.
/albums
GET – Get a list of all albums, returned as JSON.
/albums/:id
GET – Get an album by its ID, returning the album data as JSON.
On Windows:
C:\> cd %HOMEPATH%
Using the command prompt, create a directory for your code called web-service-gin.
$ mkdir web-service-gin
$ cd web-service-gin
This command creates a go.mod file in which dependencies you add will be listed for tracking. For
more about naming a module with a module path, see Managing dependencies.
Next, you’ll design data structures for handling data.
Create the data
To keep things simple for the tutorial, you’ll store data in memory. A more typical API would interact
with a database.
Note that storing data in memory means that the set of albums will be lost each time you stop the
server, then recreated when you start it.
Write the code
Using your text editor, create a file called main.go in the web-service directory. You’ll write your Go
code in this file.
Into main.go, at the top of the file, paste the following package declaration.
package main
ID string `json:"id"`
Beneath the struct declaration you just added, paste the following slice of album structs containing
data you’ll use to start.
// albums slice to seed record album data.
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
c.IndentedJSON(http.StatusOK, albums)
router := gin.Default()
router.GET("/albums", getAlbums)
router.Run("localhost:8080")
import (
"net/http"
"github.com/gin-gonic/gin"
Save main.go.
Run the code
Begin tracking the Gin module as a dependency.
At the command line, use go get to add the github.com/gin-gonic/gin module as a dependency for your
module. Use a dot argument to mean “get dependencies for code in the current directory.”
$ go get .
Go resolved and downloaded this dependency to satisfy the import declaration you added in the
previous step.
From the command line in the directory containing main.go, run the code. Use a dot argument to
mean “run code in the current directory.”
$ go run .
Once the code is running, you have a running HTTP server to which you can send requests.
From a new command line window, use curl to make a request to your running web service.
$ curl http://localhost:8080/albums
The command should display the data you seeded the service with.
[
"id": "1",
"price": 56.99
},
"id": "2",
"title": "Jeru",
"price": 17.99
},
"id": "3",
"title": "Sarah Vaughan and Clifford Brown",
"price": 39.99
You’ve started an API! In the next section, you’ll create another endpoint with code to handle
a POST request to add an item.
Write a handler to add a new item
When the client makes a POST request at /albums, you want to add the album described in the request
body to the existing albums’ data.
To do this, you’ll write the following:
Logic to add the new album to the existing list.
A bit of code to route the POST request to your logic.
Write the code
Add code to add albums data to the list of albums.
Somewhere after the import statements, paste the following code. (The end of the file is a good place
for this code, but Go doesn’t enforce the order in which you declare functions.)
// postAlbums adds an album from JSON received in the request body.
// newAlbum.
return
c.IndentedJSON(http.StatusCreated, newAlbum)
router := gin.Default()
router.GET("/albums", getAlbums)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
From a different command line window, use curl to make a request to your running web service.
$ curl http://localhost:8080/albums \
--include \
--request "POST" \
--data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'
The command should display headers and JSON for the added album.
HTTP/1.1 201 Created
Content-Length: 116
"id": "4",
"price": 49.99
}
As in the previous section, use curl to retrieve the full list of albums, which you can use to confirm
that the new album was added.
$ curl http://localhost:8080/albums \
--request "GET"
"id": "1",
"price": 56.99
},
"id": "2",
"title": "Jeru",
"price": 17.99
},
"id": "3",
"price": 39.99
},
"id": "4",
"price": 49.99
In the next section, you’ll add code to handle a GET for a specific item.
Write a handler to return a specific item
When the client makes a request to GET /albums/[id], you want to return the album whose ID matches
the id path parameter.
To do this, you will:
Add logic to retrieve the requested album.
Map the path to the logic.
Write the code
Beneath the postAlbums function you added in the preceding section, paste the following code to
retrieve a specific album.
This getAlbumByID function will extract the ID in the request path, then locate an album that matches.
// getAlbumByID locates the album whose ID value matches the id
id := c.Param("id")
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
As mentioned above, a real-world service would likely use a database query to perform this lookup.
Return an HTTP 404 error with http.StatusNotFound if the album isn’t found.
Finally, change your main so that it includes a new call to router.GET, where the path is
now /albums/:id, as shown in the following example.
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
From a different command line window, use curl to make a request to your running web service.
$ curl http://localhost:8080/albums/2
The command should display JSON for the album whose ID you used. If the album wasn’t found,
you’ll get JSON with an error message.
{
"id": "2",
"title": "Jeru",
"price": 17.99
Completed code
This section contains the code for the application you build with this tutorial.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
ID string `json:"id"`
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
c.IndentedJSON(http.StatusOK, albums)
// newAlbum.
return
c.IndentedJSON(http.StatusCreated, newAlbum)
id := c.Param("id")
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
Log on to Portal
Click Compute | Web Site. Then select Quick Create option. Provide an available URL for the new
web site and click Create Web Site.
Note
Azure is the host for a web application running in the cloud that you can control and manage. The
Quick Create option allows you to deploy a completed web application to the Azure from outside the
portal. It does not include steps for setting up a database.
Creating a new Web Site using Quick Create
Go back to the portal and click the name of the web site under the Name column to display the
management pages.
Opening the Web Site management pages
In the Dashboard page, under the quick glance section, click the Download publish profile link.
Note
The publish profile contains all of the information required to publish a web application to a Azure for
each enabled publication method. The publish profile contains the URLs, user credentials and
database strings required to connect to and authenticate against each of the endpoints for which a
publication method is enabled. Microsoft WebMatrix 2, Microsoft Visual Studio Express for
Web and Microsoft Visual Studio 2012 support reading publish profiles to automate configuration of
these programs for publishing web applications to Azure.
Download the publish profile file to a known location. Further in this exercise you will see how to use
this file to publish a web application to Azure from Visual Studio.
In the next task you will test the database connection from Visual Studio, for that reason you need to
include your local IP address in the server's list of Allowed IP Addresses. To do that, click Configure,
select the IP address from Current Client IP Address and paste it on the Start IP Address and End IP
Address text boxes and click the button.
Adding Client IP Address
Once the Client IP Address is added to the allowed IP addresses list, click on Save to confirm the
changes.
Confirm Changes
In the Settings page, under the Databases section, click the button next to your database connection's
textbox (i.e. DefaultConnection).
Then click OK. When prompted to create the database click Yes.
The connection string you will use to connect to SQL Database in Windows Azure is shown within
Default Connection textbox. Then click Next.
Connection string pointing to SQL Database
Once the publishing process finishes, your default browser will open the published web site.
Application published to Azure