API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const https = require("https"); // it's a native node module so we dont need to use npm install

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});

app.post("/", function (req, res) {
const query = req.body.cityName;
// console.log(query);
const apikey = "dd57eaafc59a1e465a30342da21d56dc";
const unit = "metric";
const url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
query +
"&appid=" +
apikey +
"&units=" +
unit;

// it need to have this strict formatting with the "https://"

// make a http get request to get data
https.get(url, function (response) {
// console.log(response);
response.on("data", function (data) {
const weatherData = JSON.parse(data); // convert data into a json object
const temp = weatherData.main.temp;
const description = weatherData.weather[0].description;
const img = weatherData.weather[0].icon;
const urlImg = "https://openweathermap.org/img/wn/" + img + "@2x.png";
// res.write("<img src=" + urlImg + ">");
res.write("<h1>the temp in " + query + " is " + temp + "degrees</h1>");
res.write("<p>the weather is like: " + description + "<p>");
res.write("<img src=" + urlImg + ">");
res.send(); // can only have one res.send method in one app dot method
});

// const object = {
// name: "dan",
// food: "potato",
// };
// console.log(JSON.stringify(object)); // turn a javascript object into a string
});
});

app.listen(3000, function () {
console.log("listening on port 3000");
});

API

  • API: Application Programming Interface
  • GUI and API:

GUI (Graphical User Interface) and API (Application Programming Interface) are integral components of software systems, with a close interconnection in facilitating user interaction and system functionality. GUIs serve as the visual interface through which users interact with software, offering intuitive controls and visual feedback. APIs, on the other hand, define the methods and protocols for communication between different software components, allowing seamless integration and interaction. The connection between GUI and API lies in their collaboration: GUIs utilize APIs to access and manipulate underlying functionalities, abstracting away the complexity of implementation details. This integration enables developers to design user-friendly interfaces while leveraging the power and flexibility of underlying systems through standardized interfaces provided by APIs. Thus, GUIs and APIs work in tandem, with APIs serving as the bridge that connects the user-facing interface of the GUI to the underlying functionality of the software system.

POST MAN

vedio

course note

Postman is a popular collaboration platform for API development used by developers and teams to simplify the process of building, testing, and managing APIs. It provides a user-friendly interface for sending HTTP requests, testing APIs, and viewing responses in various formats like JSON and XML. Postman allows users to create and organize collections of API requests, share them with team members, and collaborate on API development projects. It also offers features for automating tests, monitoring APIs, and documenting APIs with detailed descriptions and examples. Overall, Postman streamlines the API development process and enhances productivity for developers and teams.

post man is not for:

  1. user interation
  2. performance testing]
  3. security testing

HEADERS

meta information, some more additional information.

In the context of HTTP (Hypertext Transfer Protocol), a header is a part of a request or response sent between a client (such as a web browser) and a server. Headers contain additional information about the data being transmitted, such as metadata or instructions for handling the request or response.

HTTP headers consist of key-value pairs, where the key represents the header name and the value represents the data associated with that header. There are several types of headers, including:

  1. Request Headers: These are sent by the client to provide additional information about the request being made. Common request headers include “User-Agent” (providing information about the client making the request), “Accept” (indicating the media types that the client can understand), and “Authorization” (used for authentication purposes).
  2. Response Headers: These are sent by the server in response to a request and provide additional information about the server’s response. Common response headers include “Content-Type” (indicating the media type of the response body), “Content-Length” (specifying the length of the response body in bytes), and “Cache-Control” (providing caching directives).

initial value & current value

Add environment

To edit an environment variable, select the variable and change any of the following:

  • Variable - The name of the variable. Use the name to reference the variable in requests and scripts.

  • Type - If you select default, the variable value is visible in plain text. If you select secret, the variable value is masked. Learn more about variable types.

  • Initial value (shared) - This value is synced to your account using Postman’s cloud servers. It’s shared with any collaborators who have access to the environment. It’s also made public when publishing an environment along with a collection. If the value includes sensitive data, such as a password or key, you can mask the value by selecting the secret variable type.

  • Current value (local) - This value is used when sending requests in your local instance of Postman. It’s never synced to your account or shared with your team unless you choose to persist it. If you leave the current value blank, the initial value is copied to the current value when you save the environment.

    it might contain some privacy information like password and stuff.

Query Parameters

read documentation of the API

query parameters are available can only be know by reading the API documentation.

Path Variables

  1. Path Variables:
    • Path variables are placeholders within the URL’s path segment.
    • They are used to identify specific resources or endpoints.
    • Path variables are typically used for fetching or manipulating a specific resource.
    • Path variables are part of the URL’s path and are specified directly in the URL structure.
    • Example: /books/{bookId}, where {bookId} is a path variable representing a specific book’s identifier.
  2. Query Parameters:
    • Query parameters are key-value pairs appended to the end of a URL after a question mark (?).
    • They are used to provide additional information to an endpoint or to filter/query data.
    • Query parameters are commonly used for searching, filtering, sorting, or pagination purposes.
    • Query parameters do not affect the structure of the URL path and are appended to the URL after a ?, separated by & if there are multiple parameters.
    • Example: /books?genre=fiction&author=John+Doe, where genre and author are query parameters used to filter the list of books.

API authentication

POST

Json format

1
2
3
4
{
"bookId": 1,
"customerName": "John"
}

Random input data

1
2
3
4
{
"bookId": 1,
"customerName": "{{$randomFullName}}"
}

PATCH request

to update order

put the update inf in Body

JSON-> javascript object notation, its key value pairs

write API

GET : request data

POST: create a resource

PUT : update a resource

DELETE: delete a resource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/")
def home():
return "Home" # will show home on http://127.0.0.1:5000

@app.route("/get-user/<user_id>")
def get_user(user_id):
user_data = {
"user_id": user_id,
"name": "Dan",
"email": "dada@sdfs.com"
} # this is a python dictionary
extra = request.args.get("extra")
if extra:
user_data["extra"] = extra
return jsonify(user_data),200 # jsonfy the python dictionary to json data


@app.route("/create-user", methods=["POST"])
def create_user():
data = request.get_json()

return jsonify(data), 201


if __name__ == "__main__":
app.run(debug = True)