Creating your first API (with code)

Creating your first API (with code)

API: Application Program Interface allows you to communicate with an application. Every link you see is a string that you use to access the contents on a certain page. These links are nothing but APIs.

There are different types of APIs, SOAP RPC, WebSocket, and REST.

Today we will be focusing on REST API. These are the most popular and flexible APIs found on the web today. The client sends requests to the server as data. The server uses this client input to start internal functions and returns output data back to the client.


The Anatomy of an HTTP Request

An HTTP request must have the following:

  • An HTTP method (like?GET)
  • A host URL (like?https://api.spotify.com/)
  • An endpoint path(like?v1/artists/{id}/related-artists)

A request can also optionally have:

  • Body
  • Headers
  • Query strings
  • HTTP version

The Anatomy of an HTTP Response

A response must have the following:

  • Protocol version (like?HTTP/1.1)
  • Status code (like?200)
  • Status text (OK)
  • Headers

A response may also optionally have:

  • Body


Few basic concepts:

What is a resource?

In?REST, the primary data representation is called?resource. Having a consistent and robust REST resource naming strategy – will prove one of the best design decisions in the long term.

A resource can be a singleton or a collection or a sub-collection:

We can identify “customers” collection resource using the URI “/customers“. We can identify a single “customer” resource using the URI “/customers/{customerId}“.

Similarly, a singleton resource “account” inside the sub-collection resource “accounts” can be identified as follows: “/customers/{customerId}/accounts/{accountId}“.


HTTP POST request

We use?POST?to create a new resource. A?POST?request requires a body in which you define the data of the entity to be created.

HTTP GET request

We use?GET?to read or retrieve a resource. A successful?GET?returns a response containing the information you requested.

HTTP PUT request

We use?PUT?to modify a resource.?PUT?updates the entire resource with data that is passed in the body payload. If there is no resource that matches the request, it will create a new resource.

HTTP DELETE request

We use?DELETE?to delete a resource. In our weather app, we could use?DELETE?to delete a city we no longer wanted to track for some reason.


Data can also be retrieved via POST requests. If there are too many parameters in the data you are trying to access, you might use a post request and a request body in the form of JSON to send the request and read the data. GET requests don't have a request body, so all parameters must appear in the URL or in a header. While the HTTP standard doesn't define a limit for how long URLs or headers can be, most HTTP clients and servers have a practical limit somewhere between 2 kB and 8 kB.

Creating your first API Code:

openapi: 3.0.
info:
? title: Creating my first API
? version: 1.0.11

paths:
? /getStudentInfo:
? ? post:
? ? ? tags:
? ? ? ? - Student
? ? ? summary: Get information about existing student.
? ? ? description: Get information about existing student.
? ? ? operationId: checkStudent
? ? ? requestBody:
? ? ? ? description: Get information about existing student.
? ? ? ? content:
? ? ? ? ? application/json:
? ? ? ? ? ? schema:
? ? ? ? ? ? ? $ref: '#/components/schemas/Student'


? ? ? ? required: true
? ? ? responses:
? ? ? ? '200':
? ? ? ? ? description: Successful operation
? ? ? ? ? content:
? ? ? ? ? ? application/json:
? ? ? ? ? ? ? schema:
? ? ? ? ? ? ? ? $ref: '#/components/schemas/StudentResponse'? ? ? ? ??
? ? ? ? '400':
? ? ? ? ? description: Student ID supplied
? ? ? ? '404':
? ? ? ? ? description: Student not found
? ? ? ? '405':
? ? ? ? ? description: Validation exception
? ? ? ? ? ??
#Nothing in the following object affects the API unless referenced with the API.
components:
? schemas:
? ? Student:
? ? ? type: object
? ? ? properties:
? ? ? ? StudentId:
? ? ? ? ? type: integer
? ? ? ? ? format: int64
? ? ? ? ? example: 186754002
? ? ? ? Date of Birth:
? ? ? ? ? type: string
? ? ? ? ? example: 02/13/1998
? ? ? ? DepartmentId:
? ? ? ? ? type: integer
? ? ? ? ? format: int32
? ? ? ? ? example: 3122
? ? ? ??
? ? StudentResponse:
? ? ? type: object
? ? ? properties:
? ? ? ? StudentId:
? ? ? ? ? type: integer
? ? ? ? ? format: int64
? ? ? ? ? example: 186754002
? ? ? ? Email:
? ? ? ? ? type: integer
? ? ? ? ? format: int32
? ? ? ? ? example: [email protected]
? ? ? ? First Name:
? ? ? ? ? type: string
? ? ? ? ? example: John
? ? ? ? Last Name:
? ? ? ? ? type: string
? ? ? ? ? example: Doe
? ? ? ? Department:
? ? ? ? ? type: string
? ? ? ? ? example: Computer Science??        


Copy and paste the above code into https://editor.swagger.io/ and you will be able to visualize and play around with APIs a little more.

The APIs are defined in the path section. Within each API there is a list of keys. The important ones are the request and response in the above code where you need to define the structure in the schema.

As you can see above, I am GETting information however I am using POST request, the reason for doing so is that my lookup parameters could be many and I wouldn't always want to pass them in the URL.

That being said you can achieve the same result using a GET request. I wanted to demonstrate diversity in creating the same functionality.

The final test API might look something like this (not the one which you will host on your website)-

https://vpc324324938923.executeapiuseast1.teststudentdatabase.com/getStudentInfo


The above code only creates an API. Period. The API has no front end or back end. However it is functional, i.e. if tested in SOAP UI or POSTMAN, it might throw an error implying API not doing anything, but it won't throw an error implying API doesn't exist.

It’s like a door to your house. The main door of your building is

https://vpc-324324-938923.execute-api-us-east-1.teststudentdatabase.com

you might have a key or a fob to enter your building which acts like the headers.

/getStudentInfo is the door to your apartment. What you see upon opening the door (connecting to the API) is dependent on what you have placed in the house. Currently, there is nothing in the house. We have only built a door. The keys to your apartment are basically the input parameters you pass to retrieve data.

These are the basics of creating an API. As we start to build APIs in the real world, you will have to create VPCs to test the APIs in your environment in a safe environment to make sure they function properly, buy domain names from places like godaddy.com which represents your company, attach the API to various other applications like Lambda Functions or SQS in AWS. Or connect to some other server.

If you want to read more on integrating APIs with other services, there is a simple blog -?https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html


References: https://aws.amazon.com/what-is/api/

https://restfulapi.net/

https://www.freecodecamp.org/news/http-request-methods-explained/

https://www.baeldung.com/java-openapi-generator-server

要查看或添加评论,请登录

社区洞察

其他会员也浏览了