Showing posts with label header. Show all posts
Showing posts with label header. Show all posts

Sunday, 12 December 2021

FastAPI: Declare a header with multiple values

To declare a header with multiple values, define the header with list type declaration.

 

Example

@app.get("/demo")
def headers_demo(
    x_my_keys: Optional[List[str]] = Header(None)):
    return {"x_my_keys" : x_my_keys}

 

Find the below working application.

 

headerWithMultipleValues.py

 

from fastapi import FastAPI, Header
from typing import Optional, List

app = FastAPI()

@app.get("/demo")
def headers_demo(
    x_my_keys: Optional[List[str]] = Header(None)):
    return {"x_my_keys" : x_my_keys}

 

Open terminal and execute the command ‘uvicorn headerWithMultipleValues:app --reload’.

 

$ uvicorn headerWithMultipleValues:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28471] using statreload
INFO:     Started server process [28473]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

  Open the url ‘http://localhost:8000/docs’ in browser and experiment with the api ‘GET /demo’.

 


 

 

 

Previous                                                    Next                                                    Home

Saturday, 19 June 2021

Spring integration: GatewayHeader: Add headers at Gateway

You can add headers to a message using gateway.

 

How to add headers using @MessagingGateway annotation

‘defaultHeaders’ attribute is used to custom message headers. These default headers are created for all methods on the service-interface.

 

Example

@MessagingGateway(defaultHeaders = {@GatewayHeader(name = "root-header", value = "root123")})
public interface CustomGateway {

}

How to add headers using @Gateway annotation?

'headers' attribute is used specify additional headers that will be added to the request message.


@Gateway(requestChannel = "printChannel", headers = {
		@GatewayHeader(name = "secret", value = "my-secret123"),
		@GatewayHeader(name = "service-name", value = "my-service") })
public String sendToPrintChannel(String message);

 

Find the below working application.

 

Step 1: Create new maven project ‘gateway-headers-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>gateway-headers-demo</artifactId>
	<version>1</version>

	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-integration</artifactId>
		</dependency>

	</dependencies>

</project>

Step 3: Define gateway.

 

CustomGateway.java

package com.sample.app.gateway;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.*;

@MessagingGateway(defaultHeaders = {@GatewayHeader(name = "root-header", value = "root123")})
public interface CustomGateway {

	@Gateway(requestChannel = "printChannel", headers = {
			@GatewayHeader(name = "secret", value = "my-secret123"),
			@GatewayHeader(name = "service-name", value = "my-service") })
	public String sendToPrintChannel(String message);

}


Step 4: Define service activator.

 

PrintService.java

package com.sample.app.service;

import java.util.Map;
import java.util.Set;

import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
public class PrintService {

	@ServiceActivator(inputChannel = "printChannel")
	public String consumeStringMessage(Message<String> message) {
		System.out.println("Received message from printChannel : " + message.getPayload());
		
		Set<Map.Entry<String, Object>> messageHeaders = message.getHeaders().entrySet();
		
		System.out.println("Headers are.....");
		for(Map.Entry<String, Object> entry: messageHeaders) {
			System.out.println(entry.getKey() + " -> " + entry.getValue());
		}
		
		return "Success";
	}
	

}


Step 5: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sample.app.gateway.CustomGateway;

@SpringBootApplication
@Configuration
public class App {

	@Autowired
	private CustomGateway customGateway;

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Bean
	public CommandLineRunner demo() {
		return (args) -> {

			String reply = customGateway.sendToPrintChannel("Hello World");
			
			System.out.println("reply : " + reply);
		};

	};

}


Total project structure looks like below.




Run App.java, you will see below messages in console.

Received message from printChannel : Hello World
Headers are.....
service-name -> my-service
replyChannel -> org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@64712be
errorChannel -> org.springframework.messaging.core.GenericMessagingTemplate$TemporaryReplyChannel@64712be
root-header -> root123
secret -> my-secret123
id -> f3f45661-6f2e-b0c4-5503-04c302aeb937
timestamp -> 1617701164345
reply : Success


You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/spring-integration/gateway-headers-demo



 

Previous                                                    Next                                                    Home

Friday, 27 December 2019

NGINX: expires: Set Expires and Cache-Control headers


Using ‘expires’ directive, you can set Expires and Cache-Control headers.

Syntax:  expires [modified] time;
expires  epoch | max | off;
Default: expires off;
Context: http, server, location, if in location

Example
expires    24h;
expires    modified +24h;
expires    @24h;
expires    0;
expires    -1;
expires    epoch;
expires    $expires;

Example in location context
location = /about{
  add_header url "/about";
  add_header version "1.23.4";

  expires 5m;
           
  return 200 "Hello Welcome to NGINX";
}

nginx.conf
events {
}

http {
    include mime.types;

    # Buffer size for POST submissions
    client_body_buffer_size 10K;
    client_max_body_size 4m;

    # Buffer size for Headers
    client_header_buffer_size 1k;

    client_body_timeout 60s;

    client_header_timeout 60s;

    keepalive_timeout 75s;

    send_timeout 60s;

    server {
        listen 9090;

        server_name localhost;

        location = /about{
            add_header url "/about";
            add_header version "1.23.4";
           
            expires 2m;
 
            return 200 "Hello Welcome to NGINX";
        }

        location = /not_found{
            return 404 "File can't be found";
        }
    }
}


Validate and reload the configuration
$sudo nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$
$sudo nginx -s reload


When I hit the url ‘localhost:9090/about’, I can see Expires and Cache-Control response headers.
$CURL -I localhost:9090/about
HTTP/1.1 200 OK
Server: nginx/1.17.3
Date: Wed, 16 Oct 2019 15:03:04 GMT
Content-Type: text/plain
Content-Length: 22
Connection: keep-alive
Expires: Wed, 16 Oct 2019 15:05:04 GMT
Cache-Control: max-age=120
url: /about
version: 1.23.4


Previous                                                    Next                                                    Home